Closed sadir closed 7 years ago
Good question! The best way to be sure is to verify it ;) Let's change the function to print each args:
defmodule MyModule do
def fun(a, b \\ 1, c, d \\ 2) do
IO.puts "a = #{a}"
IO.puts "b = #{b}"
IO.puts "c = #{c}"
IO.puts "d = #{d}"
end
end
$ iex test.exs
iex> MyModule.fun(:arg_1, :arg_2, :arg_3)
a = arg_1
b = arg_2
c = arg_3
d = 2
If you think about it, it makes sense. If a single default arg is omitted when calling a fun, then the right-most arg with a default (in our case the arg d
) will have the default value.
Does that make sense?
Yep! Perfect sense thank you. It doesn't cover both /3 options, and d will be the default value of 2 unless you supply all four arguments, because elixir matches to the left. I have a Ruby background so this is in line with my assumptions. Thanks for your help!
Hi,
I'm working my way through your book - it's been great so far. Thanks.
I have reached chapter 2, page 28 where it is written that:
It is clear to me how the /2 and /4 arity functions would be generated. But there are two options for the /3 arity function - how does it generate one function which satisfies both conditions?