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

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
water
I’m aware of 2 such projects, are there others? git: GitHub - team-alembic/realworld: A fullstack Phoenix LiveView application with back...
New
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
peck
Hi everyone. My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
bradley
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
unaware8150
Hello folks! So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
Alvinkariuki
How Can I Optimise Compile Time Dependencies I have been building an elixir application for about 2 years now. Many modules and files ha...
New

Other Trending Topics Top

KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New
budgie
I love Elixir. It’s one of 2 programming languages I’ve ever fallen in love with. But I don’t use it anymore. Serverless was the promis...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews