[英]tail recursive call in elixir and default parameters
I am writing a simple example in Elixir and although it works I don't really understand how. 我在Elixir中写了一个简单的例子,虽然它有效但我真的不明白怎么做。
defmodule MyList do
def sum([],acc \\ 0), do: acc
def sum([head | tail], acc), do: sum(tail,acc + head)
end
When I call MyList.sum I get the expected result 当我调用MyList.sum时,我得到了预期的结果
sum([]) => 0
sum([1,2,3]) => 6
I cannot add a default param in the second sum because the compiler throws an error 我无法在第二个和中添加默认参数,因为编译器会抛出错误
def sum/2 has default values and multiple clauses, use a separate clause for declaring defaults
So my question is, how come sum([1,2,3]) works? 所以我的问题是,sum([1,2,3])如何运作? It does not match any of the definitions.
它与任何定义都不匹配。 Is the function still tail recursive?
该函数仍然是尾递归的吗?
When you have a multiclause with optional arguments, you can specify defaults as a body-less clause: 如果您有带可选参数的多重语句,则可以将默认值指定为无主体子句:
defmodule MyList do
def sum(list, acc \\ 0) # sets up default arguments
def sum([],acc), do: acc
def sum([head | tail], acc), do: sum(tail,acc + head)
end
Regarding your example, I'm just guessing, but I think that your code amounts to something like following: 关于你的例子,我只是猜测,但我认为你的代码总是如下:
defmodule MyList do
# implicitly generated due to default argument
def sum(list), do: sum(list, 0)
def sum([],acc), do: acc
def sum([head | tail], acc), do: sum(tail,acc + head)
end
Which is why sum([1,2,3])
works as well. 这就是
sum([1,2,3])
适用的原因。
Edit : The function is definitely tail recursive. 编辑 :该函数绝对是尾递归。 If the last thing a function does is a call of another function (or itself), then it is a tail call.
如果一个函数做的最后一件事是另一个函数(或它自己)的调用,那么它就是一个尾调用。 So in this case, when we call
sum(tail, acc + head)
, first the arguments are calculated, and then a tail recursive call happens. 所以在这种情况下,当我们调用
sum(tail, acc + head)
,首先计算参数,然后发生尾递归调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.