nhpip

nhpip

Why do we need to use Enum.into(%{})?

I know this is a really minor peeve, but why is this the case?:

iex(cs@localhost)54> %{key1: :i_am_a_map_whooot} |> Enum.map(&(&1))
[key1: :i_am_a_maaa___list__what_the?]

Yes I know that all I need to do is |> Enum.into(%{}) but why? Why shouldn’t the ouput type be the same as the input type?

I’m sure this has been asked 1000 times before.

Marked As Solved

wojtekmach

wojtekmach

Hex Core Team

The output type of Enum.map (and most Enum functions) cannot be the same as the input type because Enum works on a variety of data types through the Enumerable protocol. A simple example is:

iex> Enum.map(1..3, & &1 ** 2)
[1, 4, 9]

We couldn’t possibly keep the shape of the input, %Range{}, because the end result would be nonsensical. Some other things that implement Enumerable protocol are file streams and even infinite streams.

As was mentioned before there used to be a Map.map/2 but it got deprecated because a similar function existed all along, Map.new/2:

iex> Map.new(1..3, fn i -> {i, i ** 2} end)
%{1 => 1, 2 => 4, 3 => 9}

so yeah, long story short, in your particular case instead of Enum.map/2 use Map.new/2.

Also Liked

hauleth

hauleth

Still, the structure preserving Enum.map would be not possible in case like:

map = %{2 => 1, 3 => 7}

Enum.map(map, fn {a, b} -> a + b end)
Marcus

Marcus

As mentioned before, Enum.map on a map returns a list because this would fit better to pipes without the need to convert to a list and back behind the scenes in every step.

There used to be the Map.map/2 function in Elixir, which is now deprecated. But you get the same result with Map.new/2.

iex(1)> map = %{a: 1, b: 2, c: 3}
%{c: 3, a: 1, b: 2}
iex(2)> Map.map(map, fn {key, value} -> {key, value * value} end)
warning: Map.map/2 is deprecated. Use Map.new/2 instead (invoke Map.from_struct/1 before if you have a struct)
└─ iex:2

%{c: {:c, 9}, a: {:a, 1}, b: {:b, 4}}
iex(3)> Map.new(map, fn {key, value} -> {key, value * value} end)
%{c: 9, a: 1, b: 4}
sodapopcan

sodapopcan

One thing is that the result of your map operation is in a predictable order. I don’t have a real world example of where this would particularly useful, but in a pipeline it could be. Having each result getting converted back to a map would be pretty chaotic.

dimitarvp

dimitarvp

Yep, I also checked the Elixir source a while ago. IMO doing Map.new only once is more performant than doing N times Map.put so I am always doing that.

wojtekmach

wojtekmach

Hex Core Team

I’m not sure how to respond to that. Fwiw this quote from docs might be helpful:

https://hexdocs.pm/elixir/1.16.2/Collectable.html#module-why-collectable

The Enumerable protocol is useful to take values out of a collection. In order to support a wide range of values, the functions provided by the Enumerable protocol do not keep shape. For example, passing a map to Enum.map/2 always returns a list.

This design is intentional. Enumerable was designed to support infinite collections, resources and other structures with fixed shape. For example, it doesn’t make sense to insert values into a Range, as it has a fixed shape where only the range limits and step are stored.

The Collectable module was designed to fill the gap left by the Enumerable protocol.

Where Next?

Popular in Questions Top

gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

Other popular topics Top

William
I would like to know that is there any online source for learning Phoenix Framework for building E-Commerce Store? Any advantage on build...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New

We're in Beta

About us Mission Statement