Home > Software engineering >  Summation Elixir
Summation Elixir

Time:11-03

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.

CodePudding user response:

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)

CodePudding user response:

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)

  • Related