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.
source
share