Get specific key and the rest of map with Pattern Matching in Elixir

Im trying to get one element and the rest of the map with pattern matching but I’m only get compile errors.

I came up with this:

%{“One” => one | tail} = %{“One" => 1, "Three" => 3, "Two" => 2}

But I got compile errors saying that it was expected key-value pairs.

The behavior that I’m trying to achieve is:

%{“One” => one | tail} = %{“One" => 1, "Three" => 3, "Two" => 2}
one = 1
tail = %{"Three" => 3, "Two" => 2}

In elixir there is a way to acomplished that?

It sounds like you want to use Map.pop/3

iex(1)> {value, map} = Map.pop(%{"One" => 1, "Three" => 3, "Two" => 2}, "One")
{1, %{"Three" => 3, "Two" => 2}}
iex(2)> value
1
iex(3)> map
%{"Three" => 3, "Two" => 2}
3 Likes

Note that you get that error because on %{"One" => one | tail} the | is used to update the key, in your case is like that you are trying to update the tail key but missing the value.

2 Likes

A bit late to the party, but if you want to pattern match in a function definition, you can also capture the whole map:

defmodule Foo do
  def foo(map = %{"One" => one}) do
    rest = Map.delete(map, "One")
    IO.inspect(%{one: one, rest: rest})
  end
end
 Foo.foo(%{"One" => 1, "Three" => 3, "Two" => 2})
# > %{one: 1, rest: %{"Three" => 3, "Two" => 2}}
2 Likes