1

I'm trying to understand how to properly define a function with multiple clauses and optional parameters. When I write

  def sum([], total \\ 0), do: total
  def sum([h|t], total), do: h + sum(t, total)

(question Elixir default parameters for named functions with multiple clauses)

I get the warning:

warning: def sum/2 has multiple clauses and also declares default values. 
In such cases, the default values should be defined in a header. 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

I feel like the definition of sum follows this recommendation.

Could anyone explain why this is happening and what is the right way to define sum and eliminate the warning.

My version of elixir is 1.12.2.

Thanks in advance

mszmurlo
  • 1,250
  • 1
  • 13
  • 28

1 Answers1

7

Declare a head clause without do block with defaults

def sum(list, total \\ 0) # ⇐ THIS

def sum([], total), do: total
def sum([h | t], total), do: h + sum(t, total)
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160