(Protocol.UndefinedError)协议枚举未实现3 [英] (Protocol.UndefinedError) protocol Enumerable not implemented for 3
本文介绍了(Protocol.UndefinedError)协议枚举未实现3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在理解之后返回总计金额。这是我正在尝试的:
I'm trying to return a summed amount after a comprehension. Here is what I'm trying:
range = 1..999
multiple_of_3_or_5? = fn(n) -> (rem(n, 3) == 0 || rem(n, 5) == 0) end
for n <- range, multiple_of_3_or_5?.(n),
do: Enum.reduce(n, 0, fn(x, y) -> (x + y) end)
<这似乎应该总结从理解中返回的列表,而是打印此错误:
This seems like it should sum the list that is returned from the comprehension but instead it prints this error:
#=> ** (Protocol.UndefinedError) protocol Enumerable not implemented for 3
任何人都可以帮助这个? p>
Can anyone help with this?
推荐答案
你正在传递每个整数,而不是过滤的列表。您应将的结果传递给 Enum.reduce / 3
:
You're passing each integer to reduce instead of the filtered list. You should pass the result of the for
to Enum.reduce/3
:
iex(1)> range = 1..999
1..999
iex(2)> multiple_of_3_or_5? = fn(n) -> (rem(n, 3) == 0 || rem(n, 5) == 0) end
#Function<6.118419387/1 in :erl_eval.expr/5>
iex(3)> for(n <- range, multiple_of_3_or_5?.(n), do: n) |> Enum.reduce(0, fn(x, y) -> (x + y) end)
233168
您还可以使用 Enum.sum / 1
来缩短这一点:
You can also use Enum.sum/1
to shorten this:
iex(4)> Enum.sum for n <- range, multiple_of_3_or_5?.(n), do: n
233168
这篇关于(Protocol.UndefinedError)协议枚举未实现3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文