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

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
jaybe78
Hello, I’m developing a online persistent chat system (what’s app) like using elixir/dynamodb/aws for a mobile app(flutter). The diffic...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
matt-savvy
Anyone here using Honeybadger? My Honeybadger account is being overwhelmed with noise from some bots. Seeing a lot of Bandit.HTTPError...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New

Other Trending Topics Top

garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New
webofbits
Aludel - LLM Evaluation Workbench Aludel is an embeddable Phoenix LiveView dashboard for evaluating and comparing LLM prompts across mult...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews