我想找到第一个负数之前的所有正数的总和。
我在 elixir 中得到了以下列表。
iex(4)> steps = [0,1,2,3,-4,5,6,-1]
我计算这个列表的总和如下
Enum.reduce(steps,0,fn x,acc -> acc=acc+x end)
一旦我们达到负数,如何摆脱?
最佳答案
使用 Enum.reduce_while
https://hexdocs.pm/elixir/Enum.html#reduce_while/3
[1,2,3,-4,5,6,-1] |> Enum.reduce_while(0, fn x, acc ->
if x > 0, do: {:cont, acc + x}, else: {:halt, acc}
end )
关于erlang - 我怎样才能在 Elixir 中摆脱 Enum.reduce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52432333/