In the book of Sasa Juriç in 2.3.3. there is this example

``````defmodule MyModule do
def fun(a, b \\ 1, c, d \\ 2) do
a+b+c+d
end
end
``````

Then it reads " So the previous code generates three functions: MyModule.fun/2,
MyModule.fun/3, and MyModule.fun/4"

Could somebody explain which functions would be generated in this case exactly?

TIA<
Arie

1 Like
``````def fun(a, c) do
fun(a, 1, c)
end
def fun(a, b, c) do
fun(a, b, c, 2)
end
def fun(a, b, c, d) do
a + b + c + d
end
``````
5 Likes

Thx, That was not quite intuïtive for me!
In many languages optional parameters should be in last position, hence the confusion.

1 Like

So to be clear, it is not particularly idiomatic to mix required and optional parameters as the example you gave has. Sometimes you get an optional parameter at the beginning IE

``````def some_message(process_name \\ __MODULE__, arg) do
GenServer.call(process_name, arg)
end
``````

but the vast majority of the time it’s a best practice to leave defaults as the last argument(s). However as you observed the compiler is happy to handle any case.

3 Likes