Defining functions with default arguments
In Elixir, named functions (defined with the def
macro) can accept arguments and sometimes, it is convenient to assume them as optional by defining a default value or expression. Default values for function arguments are defined using \\
after the argument name.
Note
If we define a foo(a, b, c \\ 0)
function and c
has a default value, although the function can be invoked as foo(1,3)
with arity 2, the function foo/3
is executed, in this case, as foo(1,3,0)
. We don't explicitly pass a value for c
but it will take the defined value, in this case, 0
.
Getting ready
Load the Defaults
file module inside IEx and open the file defining the module (defaults.ex
) inside your favorite code editor:
> iex defaults.ex [Defaults]
How to do it…
To define functions with default arguments, follow these steps:
Define a
sum
function in theDefaults
module by adding the following code todefaults.ex
:def sum(a, b \\ 1, c \\ 1) do a + b + c end
Save the file and reload it...