Pattern Matching Basics

This lesson is included with any free account. Sign in to keep watching.
Sign in to watch →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):
<span class="hljs-comment">#a simple assignment</span>
pattern = <span class="hljs-string">"match"</span>
<span class="hljs-string">"pat"</span> <> tern = <span class="hljs-string">"pattern match"</span>
<span class="hljs-comment">#a little weirder, the variable 'tern' = "tern match"</span>
[<span class="hljs-number">1</span>, x, <span class="hljs-number">5</span>] = [<span class="hljs-number">1</span>, <span class="hljs-number">10</span>, <span class="hljs-number">5</span>]
<span class="hljs-comment">#something straightforward: x = 10</span>
This is, in a sense, destructuring assignment that you would see in JavaScript, Ruby, ES6:
<span class="hljs-keyword">var</span> [x, y, z] = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>];
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.
Lesson notes are included with any free account. Sign in to continue.
Sign in to read →