Elixir default parameters for named functions with multiple clauses

此生再无相见时 提交于 2019-12-07 10:58:33

问题


I have trouble understanding how default parameters interact with multiple clauses in named functions. It boils down to, why does the following snippet work?

defmodule Lists do

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

end

From my understanding this gets expanded by the compiler into:

defmodule Lists do

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

end

So I would expect the following to happen:

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

instead it works:

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

Using Elixir 0.12.4.


回答1:


Actually, def sum([], total \\ 0), do: total will define a function clause that looks like def sum(list), do: sum(list, 0). So I can definitely see your confusion. I will guarantee we emit a warning for such cases in future releases. Thank you!



来源:https://stackoverflow.com/questions/22080713/elixir-default-parameters-for-named-functions-with-multiple-clauses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!