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
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?
def fun(a, c) do
fun(a, 1, c)
def fun(a, b, c) do
fun(a, b, c, 2)
def fun(a, b, c, d) do
a + b + c + d
Thx, That was not quite intuïtive for me!
In many languages optional parameters should be in last position, hence the confusion.
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
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.