minhajuddin
While writing code, I always prefer using Enum.map instead of Enum.reduce, if possible, as the Enum.map version tends to be more readable, and I try to tell others to do the same, I wanted to know what you guys feel about this. Is this a good thing/bad thing?
Here are a few examples:
users = [
%User{id:1, name: "Mujju"},
%User{id:2, name: "Zainu"},
]
# reduce version
Enum.reduce(users, %{}, fn user, acc -> Map.put(user.id, user) end)
# map version
Enum.map(users, fn user -> {user.id, user} end) |> Map.new
Trending in Questions
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
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
Hello,
I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind.
However, when I launch mix phx.server, I get an error...
New
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
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
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
I’m working on a small exercise involving update_in/3, and I came up with this solution:
data = %{
name: "Periodic Table",
category:...
New
Other Trending Topics
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
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
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
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
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
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
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #ai
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixirconf-us
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #elixirconf-eu
- #api
- #forms
- #security
- #metaprogramming











Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
madeinussr
Personally, I think they both are good and serve different goals. As for your example, I would use reduce because at the start of a code line
Enum.reduceI understand what to expect from this line (and there is no need to know that you can initialize new map with a list of tuples, as in the second line (even it’s not so difficult, though)).AFAIK
mapitself implemented withreduceso we can omit additional functions invocations (inside Map.new) (like in the ‘synonym’ implementation of the second example).wmnnd
An alternative to using
Map.new(tuples)would beEnum.into(tuples, %{}), by the way.I agree with @madeinussr that this is probably mostly up to personal taste.
However, I would prefer
Enum.mapbecause the intent here is to transform each individual value (i. e. map it). So while you might not be able to tell from the initialEnum.mapthat you’ll get a Map back, it is always safe to assume you will get a transformed value that structurally resembles your input.madeinussr
Well, I understood the example’s intent as “Get the list of users and construct a map based on it”, not “Transform each user in the list”. If you just want transform every item in a list - use
map. If you want to get something new (different type) from an input - usereduce. IMHOwmnnd
Oh you’re absolutely right and in this case
Map.reducewould definitely be the better choice.minhajuddin
The example was a bit contrived. There are a few places where there is no way around using a reduce, but in a few other places we can do with
Enum.map, and in those instances I preferEnum.mapanother example
NobbZ
Let me answer this question 2 times. One answer will be generic and the other one will be specialised to the question.
In general
mapandreduceover anEnumare totally different concepts.To
mapmeans to apply a function to every element of anEnumand gives you a List which can be transformed into anEnumwhich has the same shape as the original data.On the other hand we have
reduce, which applies a function to each element and a moving accumulator to finaly reduce the completeEnuminto a single value. There is no guarantee that you can reconstruct the original shape of data and not even a guarantee that your result is anEnum!So choosing which one you choose totally depends on what kind of data you need after the iteration of the
Enum.Answering the question with the actual examples in mind is a bit harder, since we might tend here to rely on well known implementation details in the stdlib.
Since we want to retain the shape of the original data, the
data |> Enum.map(f) |> Enum.into(%{})(orMap.new/1) is preferable semantically. Currently it is in fact not as fast asreduceing directly, since it is reducing about two times due to implementation details.So if you really need the speed, you should make sure, that you benchmark both versions with data sizes you do expect to be the average in production. Keep an eye on the result of the benchmarks and check if your choosen version is still the faster one with each elixir release, that also bumps the OTP version. There might happen optimisations in both of them, that suddenly make the semantically correct version the faster one all of a sudden.
madeinussr
… and there are a lot of various examples
Actually, in most cases
mapvsreduceusage (if their outputs are the same, of course) is a matter of taste and code readability. Sometimes it’s a matter of performance.I’ve just tried to explain my choice over
mapvsreducein specific example.mkunikow
If you can use map use map. With reduce you can do more than in map. You can think as map is subset of reduce → you can write implementation of map using reduce function but you can do do otherwise.
For example you can use reduce to transform list to map, or you can use reduce to transform list to int (count number of elements in list)
Qqwy
Enum.maphas been defined underwater in terms ofEnum.reduce.(or more astutely,
Enum.mapandEnum.reduceare both thin wrappers aroundEnumerable.reduce, which does the actual reducing.)Enum.mapis not a true map (the map that is part of the Functor Algebraic Data Type): If it would be, mapping over a Range would return a Range, mapping over a File would return a File and mapping over a Tree would return a Tree.But alas, this is not the case:
Enumerableis in fact a protocol that specifies the ADT frequently known as ‘Foldable’.Enum.mapmight thus more properly be named:Enum.to_list_then_map. The order of elements in this resulting list only matters if they mattered in the original enumerable (so for e.g. MapSet it does not, and when you convert a Tree into a List, there are multiple equally valid ways to do this, so pick one and stick with it).The reason that
Enum.mapwas built on top ofEnumerable.reduce(and always converts to a list) is that it allows for easy use of data types that are not Functors, such as MapSet (and other Sets): If you’d do a true map on a set that results in multiple elements in the set having the same value, then it becomes invalid (so a Set cannot expose a true Functor map).So:
Enum.maphas an arguably confusing name, as it not only the given function over a data structure, it also always converts the data structure to a list.Enum.mapis built on top ofreduce; it therefore is always possible to useEnum.reduce, but in cases where you don’t need access to the accumulator that is being built, there is no need to do so. This is simply personal preference. (You are always allowed reinvent the wheel if you really want toEnum.mapis not the answer to your problem.crusso
Alternatively: