I'm using the following code, trying to solve Étude 3-1: Pattern Matching
from the book Études for Elixir.
16 def area(:rectangle, a \\ 1, b \\ 1) do
17 a * b
18 end
19
20 def area(:triangle, a, b) do
21 a * b / 2.0
22 end
23
24 def area(:shape, a, b) do
25 a * b * :math.pi()
26 end
And I am getting the following error:
** (CompileError) geom.ex:20: definitions with multiple clauses and default values require a function head.
There's an explanation right after the error message:
Instead of:
def foo(:first_clause, b \\ :default) do ... end
def foo(:second_clause, b) do ... end
one should write:
def foo(a, b \\ :default)
def foo(:first_clause, b) do ... end
def foo(:second_clause, b) do ... end
def area/3 has multiple clauses and defines defaults in a clause with a body
geom.ex:20: (module)
(stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
Apparently I cannot use default values: Got it. But why?
You actually CAN use default values, but as the error message indicates, you need to specify a function head:
14 def area(shape, a \\ 1, b \\ 1)
15
16 def area(:rectangle, a, b) do
17 a * b
18 end
19
20 def area(:triangle, a, b) do
21 a * b / 2.0
22 end
23
24 def area(:shape, a, b) do
25 a * b * :math.pi()
26 end
Note line 14 specifying the necessary function head.
From https://elixirschool.com/lessons/basics/functions/ : Elixir doesn’t like default arguments in multiple matching functions, it can be confusing. To handle this we add a function head with our default arguments
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With