Tail recursive call in elixir and default parameters

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?

+6
source share
1 answer

When you have multitasking with optional arguments, you can specify default values ​​as a body-less clause:

 defmodule MyList do def sum(list, acc \\ 0) # sets up default arguments def sum([],acc), do: acc def sum([head | tail], acc), do: sum(tail,acc + head) end 

As for your example, I am just guessing, but I think your code comes down to the following:

 defmodule MyList do # implicitly generated due to default argument def sum(list), do: sum(list, 0) def sum([],acc), do: acc def sum([head | tail], acc), do: sum(tail,acc + head) end 

This is why sum([1,2,3]) works as well.

Edit : The function is certainly recursive. If the last thing a function does is call another function (or itself), then this is a tail call. So in this case, when we call sum(tail, acc + head) , the arguments are computed first, and then the tail recursive call comes up.

+9
source

All Articles