5

デフォルトのパラメータが名前付き関数の複数の句とどのように相互作用するか理解できません。要するに、次のスニペットが機能するのはなぜですか?

defmodule Lists do

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

end

私の理解では、これはコンパイラによって次のように拡張されます。

defmodule Lists do

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

end

したがって、次のことが起こると予想されます。

iex(1)> Lists.sum [1,2,3,4]
** (FunctionClauseError) no function clause matching in Lists.sum/1

代わりに動作します:

iex(1)> Lists.sum [1,2,3,4]
10

Elixir 0.12.4を使用しています。

4

1 に答える 1