具有多个子句的命名函数的Elixir默认参数 [英] Elixir default parameters for named functions with multiple clauses

查看:97
本文介绍了具有多个子句的命名函数的Elixir默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解默认参数如何与命名函数中的多个子句交互.归结为以下代码段为何起作用?

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

使用 Elixir 0.12.4 .

推荐答案

实际上,def sum([], total \\ 0), do: total将定义一个类似于def sum(list), do: sum(list, 0)的函数子句.因此,我绝对可以看到您的困惑.我将保证在将来的版本中针对此类情况发出警告.谢谢!

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!

这篇关于具有多个子句的命名函数的Elixir默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆