gpt4 book ai didi

Elixir:(FunctionClauseError)没有函数子句匹配

转载 作者:行者123 更新时间:2023-12-04 10:47:48 26 4
gpt4 key购买 nike

我制作了这个应该打印每个数字的 Elixir 模块,“计数”到你给它的数字。

defmodule Count do
def to(n) do
m = 1
_to(n, m)
end
defp _to(n, m) when (m <= n) do
IO.puts "#{m}"
x = m + 1
_to(n, x)
end
end

...但是当我运行它时,它的性能完全符合预期,只是它在最后抛出了这个错误。这里发生了什么?
iex(1)> Count.to 5  
1
2
3
4
5
** (FunctionClauseError) no function clause matching in Count._to/2
count.exs:6: Count._to(5, 6)
iex(1)>

感谢您的任何帮助。

最佳答案

如果没有任何子句匹配,Elixir 不会默默地忽略函数调用——你会得到一个 FunctionClauseError .在这种情况下,当 m > n , _to 中没有函数子句匹配,所以 Elixir 会抛出该错误。您需要添加另一个版本的 _to接受任何 mn (或者你可以添加一个when m > n,如果你愿意的话)并且什么都不做。

defp _to(n, m) when (m <= n) do
IO.puts "#{m}"
x = m + 1
_to(n, x)
end
defp _to(n, m) do
end

关于Elixir:(FunctionClauseError)没有函数子句匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38417903/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com