Tee
Enumerables - how does Enum.reduce work with maps
can someone please explain to me how Enum.reduce works with maps
Most Liked
al2o3cr
Using Enum.reduce ultimately delegates to the protocol function Enumerable.reduce, which is implemented for Map here:
This first converts the Map to a list of {key, value} tuples, then reduces over it.
zachgarwood
Tangentially related, I love the StackOverflow Axiom at play here: “It’s easier to get a good answer by proposing an incorrect implementation than by asking a well-stated question.”
NobbZ
That won’t work, there is no += in elixir. I think what you really mean is more like this:
alphabet_positions = %{"a" => 1, "b" => 2, "c" => 3, …}
Enum.reduce(alphabet_positions, 0, fn {letter, position}, sum ->
if letter in ~w[a e i o u], do: sum + position, else: sum
end)
NobbZ
No, its turned into a list of tuples with the key as the first element and the corresponding values as the second. The implementation of Map.to_list/1 is equivalent to this:
map
|> Map.keys()
|> Enum.reduce([], fn key, list -> [{key, map[key]} | list] end)
peerreynders
Going the other way (list to map) Map.new/2 can be helpful.
iex(1)> square_tuple = fn x -> {x , x * x} end
#Function<7.91303403/1 in :erl_eval.expr/5>
iex(2)> result = Map.new(1..10, square_tuple)
%{
1 => 1,
2 => 4,
3 => 9,
4 => 16,
5 => 25,
6 => 36,
7 => 49,
8 => 64,
9 => 81,
10 => 100
}
iex(3)>







