I’m trying to figure out the idiomatic way to group a list of maps by an atom because mix format gives me an interesting result, depending on what I try.
Here’s my input and I’d like to group by :species.
iex(7)> characters = [
...(7)> %{species: :human, name: "Calvin"},
...(7)> %{species: :human, name: "Rosalyn"},
...(7)> %{species: :feline, name: "Hobbes"}
...(7)> ]
My first approach was to be explicit by using Map.get/3:
iex(8)> characters |> Enum.group_by(&Map.get(&1, :species))
%{
feline: [%{name: "Hobbes", species: :feline}],
human: [
%{name: "Calvin", species: :human},
%{name: "Rosalyn", species: :human}
]
}
That looks pretty good.
And then I tried it with a combination of capturing and map.key syntax*, getting the same result. ![]()
iex(9)> characters |> Enum.group_by(&(&1.species))
Now for the interesting part: when the latter example is subjected to mix format the result is:
characters |> Enum.group_by(& &1.species)
To my novice eyes, that (& &1.species) part looks really weird and now I’m thinking I’m barking up the wrong tree. ![]()
I’d appreciate any thoughts. Thanks!
Extra stuff:
I found this (really cool) reply by Jose, but in this case the capture involves a tuple and mix format doesn’t change it:
(* I understand that map.key will raise when Map.get/3 will nil, and therefore they’re not exactly the same.)






















