Pattern Matching Basics

This is a premium course, which you can purchase below.

Buy Now

Pattern Matching in Elixir is one of those things that can be vexxing, interesting, or obvious. Ultimately, however, it will be confusing if you have never dealt with it before.


Let's dive right in.

Rethink Assignment

In programming, you typically assign a variable with an = sign. In math, = means something else entirely. It means the two terms on either side of the sign are equivalent. That's the way it is with Elixir.

When Elixir sees an = it will try to make both sides equivalent. When you call a function, Elixir will do the same thing with the arguments you pass: pattern matching against the function's argument list.

You've already seen a little of this in the previous chapters. Let's take a look at a few more examples (feel free to open up iex and type these examples in):

#a simple assignment
pattern = "match"

"pat" <> tern = "pattern match"
#a little weirder, the variable 'tern' = "tern match"

[1, x, 5] = [1, 10, 5]
#something straightforward: x = 10

This is, in a sense, destructuring assignment that you would see in JavaScript, Ruby, ES6:

var [x, y, z] = [1,2,3];

But Pattern Matching is a whole lot more than this. While you can indeed use it to assign values, it's much more useful when used with function calls.