Borybar
Borybar

Reputation: 781

Summation Elixir

I am trying to recreate this equation in Elixir:

enter image description here

For now I am working on an easy example and I have something like this:

Enum.each(1..2, fn x -> :math.pow(1 + 1/1, -x) end)

However, while using Enum.each I am getting an :ok output, and therefore I can't inject it later to Enum.sum()

I will be grateful for help.

Upvotes: 0

Views: 193

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

While the answer by @sabiwara is perfectly correct, one’d better either use Stream.map/2 to avoid building the intermediate list that might be huge, or directly Enum.reduce/3 to the answer.

#                 ⇓ initial value
Enum.reduce(1..2, 0, &:math.pow(1 + 1/1, -&1) + &2)

Upvotes: 4

sabiwara
sabiwara

Reputation: 3204

Enum.each/2 is for side effects, but does not return a transformed list.

You are looking for Enum.map/2.

Alternatively, you could use a for comprehension: for x <- 1..2, do: :math.pow(1 + 1/1, -x)

Upvotes: 2

Related Questions