Pattern Matching in Enum.map

I have seen this somewhere before in a similar format.
I want to pattern match on two keys in a list of maps, sometimes x will be present, sometimes y.
How I could show it:

m = [%{x: 5}, %{y: 7}] 

Enum.map(m, fn 
  %{x: x} -> 
    IO.puts("matched on x, #{x}")
  %{y: y} -> 
    IO.puts("matched on y #{y}") 
end)

Is this possible?

2 Likes

As we are iterating over a list of maps, it’ll be exactly as you drafted.

The result will be [:ok, :ok] and 2 lines of text printed to the screen.

1 Like

Yup this literally works as written:

iex(1)> m = [%{x: 5}, %{y: 7}]
[%{x: 5}, %{y: 7}]
iex(2)>
nil
iex(3)> Enum.map(m, fn
...(3)>   %{x: x} ->
...(3)>     IO.puts("matched on x, #{x}")
...(3)>   %{y: y} ->
...(3)>     IO.puts("matched on y #{y}")
...(3)> end)
matched on x, 5
matched on y 7
[:ok, :ok]
3 Likes

I tried this in my IEX and it didn’t work for 15 minutes, that’s why I posted this.
I read the above replies and then retried it and it worked!
Programming…

2 Likes