I am writing a simple example in Elixir, and although it works, I really do not understand how to do this.
defmodule MyList do def sum([],acc \\ 0), do: acc def sum([head | tail], acc), do: sum(tail,acc + head) end
When I call MyList.sum, I get the expected result
sum([]) => 0 sum([1,2,3]) => 6
I can not add the default parameter to the second amount, because the compiler throws an error
def sum/2 has default values and multiple clauses, use a separate clause for declaring defaults
So my question is: how is the sum ([1,2,3]) obtained? It does not match any of the definitions. Is the function still tail recursive?
source share