Tee

Tee

can someone please explain to me how Enum.reduce works with maps

Showing Posts 1 to 10

al2o3cr

al2o3cr

Using Enum.reduce ultimately delegates to the protocol function Enumerable.reduce, which is implemented for Map here:

https://github.com/elixir-lang/elixir/blob/79388035f5391f0a283a48fba792ae3b4f4b5f21/lib/elixir/lib/enum.ex#L3351-L3353

This first converts the Map to a list of {key, value} tuples, then reduces over it.

Tee

Tee OP

it would be nice with an example that i can relate with

zachgarwood

zachgarwood

alphabet_positions = {"a" => 1, "b" => 2, "c" => 3, ...}
Enum.reduce(alphabet_positions, 0, fn({letter, number}, accumulator) ->
  if "aeiou" =~ letter do
    accumulator += number
  end
  accumulator
end)

This trivial example adds up the positions of all the vowels in the alphabet.

peerreynders

peerreynders

Maps implement the Enumerable protocol. That implementation turns the map into a list of key-value tuples - see Map.to_list/1 (the actual implementation uses the Erlang version).

What is being reduced is the resulting list of key-value tuples, not the map itself - which goes something like this:

iex(1)> sum_values = fn {_k, v}, sum -> v + sum end
#Function<13.91303403/2 in :erl_eval.expr/5>
iex(2)> collect_keys = fn {k, _v}, others -> [k | others] end
#Function<13.91303403/2 in :erl_eval.expr/5>
iex(3)> do_both = fn {k, v}, {keys, sum} -> {[k | keys], v + sum} end 
#Function<13.91303403/2 in :erl_eval.expr/5>
iex(4)> map = %{"a" => 1, "b" => 2}
%{"a" => 1, "b" => 2}
iex(5)> keyword_list = Map.to_list(map)
[{"a", 1}, {"b", 2}]
iex(6)> values_result = List.foldl(keyword_list, 0, sum_values)
3
iex(7)> keys_result = List.foldl(keyword_list, [], collect_keys)
["b", "a"]
iex(8)> result = List.foldl(keyword_list, {[],0}, do_both)
{["b", "a"], 3}
iex(9)> 

Edit: Correction as indicated by @NobbZ

NobbZ

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

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

peerreynders

Looks like it uses an internal iterator to avoid redundant traversals:

https://github.com/erlang/otp/blob/master/lib/stdlib/src/maps.erl#L116-L127

Tee

Tee OP

Have tried this and the result is true
which can also be implented this way:
Enum.reduce(%{“a” => 1, “b” => 2}, , fn {k, v}, acc → [{k, v} | acc] end)
[{“b”, 2}, {“a”, 1}]

Tee

Tee OP

your example returns the accumalator of the last vowel which i understand it will be the initial position of the last vowel added to accumulator giving you 6

peerreynders

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)>

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews