Hello everyone. Im currently learning Elixir with the official guide, and I dont really understand why this code does not compile:
defmodule Learning do
def sum_list([head | tail], accumulator \\ 0)
def sum_list([head | tail], accumulator) do
sum_list(tail, head + accumulator)
end
def sum_list([], accumulator) do
accumulator
end
end
IO.puts(Learning.sum_list([1, 2, 3]))
As I understand thanks to the default arguments page, I created a function head with the accumulator parameter defaulting to the value 0.
Then, I just follow the code provided in the recursion page.
I simply can’t understand why is this failing.
Is it because those function clauses don’t have guards or something?
I asked chatgpt and its answer was to simply get rid of of the default argument and create a new function clause, like this:
def sum_list(list), do: sum_list(list, 0)
which seems like a different thing, with sum_list/1 instead of sum_list/2
Anyone can offer me some explanation about what I am understanding wrong here?
Thanks all.
That snippet is inside a .exs file. When I try to execute that file with the command $ elixir filename.exs, it throws the following error:
error: only variables and \\ are allowed as arguments in function head.
If you did not intend to define a function head, make sure your function definition has the proper syntax by wrapping the arguments in parentheses and using the do instruction accordingly:
def add(a, b), do: a + b
def add(a, b) do
a + b
end
│
2 │ def sum_list([head | tail], accumulator \\ 0)
│ ^
│
└─ filename.exs:2:7: Learning.sum_list/2
** (CompileError) filename.exs: cannot compile module Learning (errors have been logged)
Oh, I see where the problem is now. I was treating head and tail as parameters, even though the actual parameter was a list.
The error from the compiler made me focus on other things instead of the obvious..
Based on your feedback I’ve made a suggestive PR to improve the error message:
I have no idea if this will be accepted. This is my first contribution to Elixir itself, and seemed like low hanging fruit to clarify an error message. More clarity around errors are always a win in my book.