default-parameters - 具有多个子句的命名函数的 Elixir 默认参数

标签 default-parameters elixir

我无法理解默认参数如何与命名函数中的多个子句交互。归结为,为什么以下代码段有效?

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。

最佳答案

其实,def sum([], total \\ 0), do: total将定义一个看起来像 def sum(list), do: sum(list, 0) 的函数子句.所以我绝对可以看到你的困惑。我保证我们会在 future 的版本中针对此类情况发出警告。谢谢!

关于default-parameters - 具有多个子句的命名函数的 Elixir 默认参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22080713/

相关文章:

c++ float 组作为默认参数

python - 在python函数中传递带有varargs的默认参数

c++ - 取消引用具有默认参数的函数 - C++14 与 C++11

elixir ecto - 具有多个模式的 embed_one

elixir - Elli 与 Elixir 基本使用问题

elixir - 验证 Elixir Ecto 中的存在,但仅在插入或更新时验证

c++ - 函数 typedef 声明符 - 默认参数位置

tsql - T-SQL - 具有默认参数的函数

elixir - 如何从 Phoenix Controller 向 channel 广播消息?

docker - 模块 EEx 不可用