'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



Solution 1:[1]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aleksei Matiushkin