Pattern Matching in Elixir

Let’s talk about pattern matching and the assignment operator — there’s more to it in Elixir.

The = operator can be used to assign values to variables, like in most other language:

iex> x = 1 
1
iex> x = 2
2

The difference with Elixir is that it’s called a match operator.

  • A match is true when both the left and right sides are equal.
  • A variable can only be assigned a value when it’s on the left side i.e.

x = 1

iex> x = 1 
1
iex> 1 = x
1
iex> 2 = x
** (MatchError) no match of right hand side value: 2

As you can see, MatchError will be raised when the match fails.

The Pin Operator (^)

This operator is useful for when you want to match to a variable that already holds a value. It prevents you from reassigning the variable.

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

Destructuring Data Types

Not only can we match simple values, but complex data types are in our reach too.

Using a list:

iex> [a, b, c] = [1, 2, 3] 
[1, 2, 3]
iex> a
1
iex> b
2
...

The same matching rules apply. When they don’t match, you’ll get the expected MatchError:

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

To get passed this issue or to ignore a value, use an underscore _:

iex> [a, b, _] = [1, 2, 3] 
[1, 2, 3]

Another thing to note about using the underscore, is that you can’t retrieve any values from it. Trying to read from _ above would throw:

** (CompileError) iex:2: unbound variable _

You can also pattern match against different types. As can be seen with a list and a tuple.

Lists have square brackets [ ] while tuples use curly braces { }.

iex> [1, 2] = [1, 2] 
[1, 2]
ieX> [1, 2] = {1, 2}
** (MatchError) no match of right hand side value: {1, 2}

See you soon.


Originally published at justmegareth.com on April 13, 2017.