My current solution is to run with_index
and then reduce
on the array.
5..10
|> Stream.with_index
|> Enum.reduce(0, fn(num_idx, acc) ->
{num, idx} = num_idx
acc + num * idx
end)
Is there a method that attaches an element's index to the element and then run reduce on the array?
You have to remember that the Enum.reduce
function must have two arguments. So you need to make changes accordingly.
What you did was perfectly fine. According to your specification you can also use Enum.with_index
Alternatively you can use an accumulator as a tuple, with one element representing an index and other the result.
5..10 #Directly pattern match in argument list
|> Enum.reduce({0,0}, fn(num,{index,current_result}) ->
{index+1,current_result + num * index}
end)
Why not use Enum.with_index
?
5..10
|> Enum.with_index
|> Enum.reduce(0, fn({number, index}, acc) ->
acc + number * index
end)
.with_index
takes an enumerable and returns a keyword list with each element of the enumerable mapped to its index. So Enum.with_index([:hi, :hello, :greetings])
would return [hi: 0, hello: 1, greetings: 2]
. We can utilize the fact that Elixir keyword lists are lists of tuple pairs to pattern match in .reduce
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With