总结灵药
Summation Elixir
我正在尝试在 Elixir 中重新创建这个等式:
现在我正在做一个简单的例子,我有这样的东西:
Enum.each(1..2, fn x -> :math.pow(1 + 1/1, -x) end)
但是,在使用 Enum.each 时,我得到了一个 :ok 输出,因此我不能稍后将它注入到 Enum.sum()
我将不胜感激。
Enum.each/2
用于副作用,但不是 return 转换后的列表。
您正在寻找 Enum.map/2
.
或者,您可以使用 for
理解:
for x <- 1..2, do: :math.pow(1 + 1/1, -x)
虽然@sabiwara 的回答完全正确,但最好还是使用 Stream.map/2
to avoid building the intermediate list that might be huge, or directly Enum.reduce/3
来回答。
# ⇓ initial value
Enum.reduce(1..2, 0, &:math.pow(1 + 1/1, -&1) + &2)
我正在尝试在 Elixir 中重新创建这个等式:
现在我正在做一个简单的例子,我有这样的东西:
Enum.each(1..2, fn x -> :math.pow(1 + 1/1, -x) end)
但是,在使用 Enum.each 时,我得到了一个 :ok 输出,因此我不能稍后将它注入到 Enum.sum()
我将不胜感激。
Enum.each/2
用于副作用,但不是 return 转换后的列表。
您正在寻找 Enum.map/2
.
或者,您可以使用 for
理解:
for x <- 1..2, do: :math.pow(1 + 1/1, -x)
虽然@sabiwara 的回答完全正确,但最好还是使用 Stream.map/2
to avoid building the intermediate list that might be huge, or directly Enum.reduce/3
来回答。
# ⇓ initial value
Enum.reduce(1..2, 0, &:math.pow(1 + 1/1, -&1) + &2)