Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do reduce with index in Elixir?

Tags:

elixir

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?

like image 523
domp Avatar asked Nov 03 '15 05:11

domp


2 Answers

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)
like image 117
coderVishal Avatar answered Oct 31 '22 03:10

coderVishal


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.

like image 20
Fomentia Avatar answered Oct 31 '22 01:10

Fomentia