mrkurt
Map over a map and create a new map?
Hello! I’m trying to get more comfy with idiomatic elixir, and it seems like one line anonymous fn {} -> ... end calls might not be ideal. Maybe they are, but I’m curious if there’s a cleaner way to do a map over a map and get another map.
Here’s what I have:
Enum.map(m, fn {k,v}-> {k, length(v)} end) |> Map.new
Is there a way to write this more concisely? At first I thought capture syntax might be the way, but I can’t find a function to capture that creates a tuple.
And for bonus points, can you destructure capture arguments? Because I also have one of these guys:
|> Enum.flat_map(fn {_, %{metas: metas}} -> metas end)
—edit—
For the second example, I came up with this (which does indeed make me happier):
|> Map.values
|> Enum.flat_map(&Map.get(&1, :metas))
Marked As Solved
sabiwara
Actually Map.new/2 accepts a function, so you can also directly call Map.new(m, fn {k,v}-> {k, length(v)} end).
Also Liked
kokolegorille
What about skipping the first Enum.map?
Map.new(m, & {elem(&1, 0), String.length(elem(&1, 1))})
You can also use for with reduce.
for {k, v} <- m, reduce: %{} do acc -> Map.put(acc, k, String.length(v)) end
or Enum.reduce directly
Enum.reduce(m, %{}, fn {k, v}, acc -> ... end)
kokolegorille
You might not have seen I used Map.new/2 in my reply ![]()
sabiwara
Oh sorry I missed it!
Also worth noting, Map.new/2 should be the fastest option as well according to this benchmark.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









