mszmurlo
mszmurlo

Reputation: 1339

How to define a function with multiple clauses and optional parameters in elixir

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

Upvotes: 1

Views: 852

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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)

Upvotes: 7

Related Questions