I'm new to Elixir. I have this code:
defmodule DefaultParams do
def func(p1, p2 \\ 2, p3 \\ 3, p4) do
IO.inspect [p1, p2, p3, p4]
end
end
With this code, I do:
DefaultParams.func("a", "b") #=> ("a", 2, 3, "b")
I understand why it works that way: because of pattern matching. Elixir tries to match the supplied parameters to the ones defined in the function definition.
However, I don't understand this:
DefaultParams.func("a", "b", "c") #=> ("a", "b", 3, "c")
Why is the output not ("a", 2, "b", "c")? That also fits the pattern defined in the parameters. I looked for an in-depth explanation in the docs but couldn't find anything.
After thinking about it for a while, I developed the suspicion that it works like this:
- "a" is matched to p1
- "b" is matched to p2
- "c" is not matched to p3 because then there would be a mismatch. So it is skipped, and p3 gets the default value, which is 3
- "c" is matched to p4
Can someone confirm/explain?
edit: fixed typos