(Protocol.UndefinedError) protocol Enumerable not implemented for 3

那年仲夏 提交于 2019-12-12 05:19:08

问题


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

Can anyone help with this?


回答1:


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

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


来源:https://stackoverflow.com/questions/44712655/protocol-undefinederror-protocol-enumerable-not-implemented-for-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!