Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compilation Error: "definitions with multiple clauses and default values require a function head"

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?

like image 483
Jonathan Soifer Avatar asked Aug 11 '16 12:08

Jonathan Soifer


1 Answers

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

like image 165
David Sulc Avatar answered Oct 19 '22 14:10

David Sulc