Capture operator `&` ampersand for a map - how to refer to a second variable?

Given this:


m1 = %{a: 1, b: 44, c: 66}
a1 = Enum.map(m1, fn {k, v} -> v end)

How can I do the same thing with the & operator?

a1 = Enum.map(m1, &(&2)) # doesn't compile, capture &2 cannot be defined without &1

How to refer to k and v in such cases?

Enum.map is passing elements of the map as a single argument - a {key, value} tuple. The fn version pattern-matches on that to extract the second element.

To do this with &, you’ll need to use elem explicitly:

a1 = Enum.map(m1, &elem(&1,1))
2 Likes