Pattern Matching (It’s Not a Sewing Thing)

One of the most fundamental concepts in Elixir is Pattern Matching. Rather than simple variable assignment, which is what you’ll find in most OOP languages, Pattern Matching supports and helps to protect the immutability of data, which is one of the major benefits of functional programming.

Pattern Matching relies upon two basic tenets: 1) variable binding on the left side of = (the match operator) and 2) matching the shape of the right and left hand sides of the match.

For example, consider the following simple illustration in IEx (Elixir’s equivalent to Ruby’s Pry):

Interactive Elixir (1.4.0) — press Ctrl+C to exit (type h() ENTER for help)
iex(1)> a = 1
1
iex(2)> 1 = a
1
iex(3)> 2 = a
** (MatchError) no match of right hand side value: 1
iex(4)> a = 2
2
iex(5)> 2 = a
2
iex(6)> 1 = a
** (MatchError) no match of right hand side value: 2

Pattern Matching dictates that the left and right sides of the expression must match. We first bind the value 1 to the variable a, so when we try to assert that 2 = a, we get an error. But then we’re able to bind the value 2 to the variable a, so what gives?

a is bound to 1 in the first line which means 2 cannot be bound to a. But a can be re-bound to 2. This is because variable binding only happens on the left side of the match operator! Neat, huh? If you want to avoid a being re-bound to a different value, you can use the pin operator like so:

iex(7)> ^a = 1
1
iex(8)> ^a = 2
** (MatchError) no match of right hand side value: 2

Pattern Matching also requires that the shape of the left side match the shape of the right side. What do we mean by shape? Well, if you have a Tuple (more on those later) containing two variables on the left side of the match operator, then you better have a Tuple containing two values on the right side of the match operator, as follows:

iex(9)> { a, b } = { 1, 2 }
{1, 2}
iex(10)> a
1
iex(11)> b
2

You will get a match error if you try to match an unequal number of right-hand values to the left-hand tuple. This is because the shape of the left side does not match the shape of the right side:

iex(12)> { a, b } = { 1, 2, 3 }
** (MatchError) no match of right hand side value: {1, 2, 3}

Now you have a very, extremely, supremely, truly basic overview of how Pattern Matching works. As you explore Elixir further, you will find that Pattern Matching is incredibly powerful, and it will alter the way you look at transforming data. It’s well worth your time to play around with various matches in IEx to see what works and what doesn’t. Happy coding!

Show your support

Clapping shows how much you appreciated Sonia Gupta’s story.