Pattern matching as filter

Today I learned that pattern matching is also can be addressed in Elixir.

Gaspar Chilingarov
Learn Elixir
2 min readMar 28, 2018

--

How could I’ve missed it! Of course everything which is not in Kernel.Special forms is either macros or function.

For example if we check does simple 1+2operation means

iex(3)> quote do
...(3)> 1 + 2
...(3)> end
{:+, [context: Elixir, import: Kernel], [1, 2]}
iex(4)>

We will see that it is + imported from Kernel ! :-)

Power of match?

And so is the match?

A convenience macro that checks if the right side (an expression) matches the left side (a pattern).

That basically allows you to use it in the pipes like this:

iex(1)> list = [a: 1, b: 2, a: 3] ++ [{:a, 1, 10}] 
[{:a, 1}, {:b, 2}, {:a, 3}, {:a, 1, 10}]
iex(2)> list |> Enum.filter(&match?({:a, _}, &1))
[a: 1, a: 3]

It is notable that is filters out not only based on value of first element, but also on arity of the tuple.

You can use it to filter elements which look like a maps Enum.filter(&match?(%{}, &1)) , but it is easier to use just is_map .

Matching %{key => _} will filter from list of maps only those maps which have that key [%{a: 10}, %{b: 20}] |> Enum.filter(&match?(%{a: _}, &1)) . In other way it is more readable to way to write Map.has_key? . But if you also want to check both key and value at the same time — match version may be faster.

About me

I’m Gaspar Chilingarov . I facilitate DevOps transition, help moving legacy applications to cloud and write high-performance Elixir apps.

Need help with your Elixir app or want prototype your next microservice in Elixir? DM me on Twitter or Github.

You can connect with me on Twitter, Facebook, LinkedIn and GitHub.

Found this post useful? Kindly tap the ❤ button below! :) Let’s spread word about Elixir.

--

--

Gaspar Chilingarov
Learn Elixir

I facilitate DevOps transition, help moving legacy applications to the cloud and write high-performance Elixir apps.