Default Parameters for Named Functions with Multiple Reservations

It’s hard for me to understand how the default parameters interact with several sentences in named functions. It comes down to why the following snippet works?

defmodule Lists do

  def sum([], total \\ 0), do: total
  def sum([h|t], total), do: h + sum(t, total)

end

From my understanding, this is expanded by the compiler in:

defmodule Lists do

  def sum([]), do: sum([], 0)
  def sum([], total), do: total
  def sum([h|t], total), do: h + sum(t, total)

end

So, I was expecting the following:

iex(1)> Lists.sum [1,2,3,4]
** (FunctionClauseError) no function clause matching in Lists.sum/1

instead it works:

iex(1)> Lists.sum [1,2,3,4]
10

Use of the elixir 0.12.4.

+4
source share
1 answer

Actually, it def sum([], total \\ 0), do: totalwill determine the sentence of the function, which looks like def sum(list), do: sum(list, 0). So I definitely see your confusion. I guarantee that we will issue a warning for such cases in future releases. Thanks!

+10

Source: https://habr.com/ru/post/1529300/


All Articles