Pattern Matching Basics
Buy or Subscribe
You can access this course in just a minute, and support my efforts to rid the world of crappy online courses!
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.