sasa1977 / elixir-in-action

Code samples for Elixir in Action book
947 stars 199 forks source link

Question: Default argument example explanation #15

Closed sadir closed 7 years ago

sadir commented 7 years ago

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:

You can set the defaults for any combination of arguments:

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

Always keep in mind that default values generate multiple functions of the same name with different arities. So the previous code generates three functions: MyModule.fun/2, MyModule.fun/3, and MyModule.fun/4.

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?

sasa1977 commented 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?

sadir commented 7 years ago

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!