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

Hellowman
Hello everyone! I am new to coding with Elixir/Erlang. And i am looking for some utilities for fuzzing testing like AFL++. Does anyone ...
New
yarrichar
I’m very new to Elixir, so sorry if this is a silly question: I am wondering what happens to the mailbox of a process when the machine i...
New
pragdave
How do I tell Hologram not to escape HTML when substituting into templates? {Textile.render(@product.long_description)} escapes the HTM...
New
Fl4m3Ph03n1x
Background When trying to execute mix release on a Windows 11 machine for a Phoenix project I get the following error: * assembling mark...
New
mandar1045
I load tested a plain Phoenix chat app backed by Postgres with 100 million messages in it, everything on default settings, to see what br...
New
rlipscombe
I’d like to create a file with 600 permissions (rw-------), but there’s a race condition if I create it and then change the permissions. ...
New
saleyn
Is there a way to import record definitions in the iex shell for pretty printing (similar to the rr command in the erl shell)? This woul...
New

Other Trending Topics Top

dominicletz
Hey there, I haven’t seen a list of useful Elixir specific skills for the popular AI tools yet so I’m starting one here with my first. ...
New
raa-ziq
Hi everyone :waving_hand: I wanted to share something I’ve been building — NowBlind, a random chat app designed to help people discover ...
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
OndrejValenta
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly) AI dream has many faces, but general...
New
kip
Localize is the next generation localisation library for Elixir. Think of it as ex_cldr version 3.0. The first version will be released ...
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

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews