It's been awhile since I wrote a blog post, life has been pretty busy but that doesn't mean I did not learn anything new.
For quite a bit now I was searching for something that can make me as happy as ruby did but more functional and I stumbled upon Elixir. I actually heard about Elixir and played around for a bit with it before but never tried to dig deeper.
Influenced by two of my coding comrades I got Programming Elixir book and started going through it. I am about 25% done and I think I finally found thing I was looking for. So I thought why not blog about my journey with Elixir.
This post will be devoted to something called pattern matching. The closest thing I can compare it to is ES6 destructuring but it is so much more. Let's dive in.
x = 5
In "normal" programming language you would say that you are assigning value of
5 to a variable
x. But not in Elixir. You are actually doing pattern matching. Elixir is asserting that left side is matching the right side by binding
One of the reasons I really love Elixir is that it has a lot of math in it. So we all remember the way that simple equations work ?
x = a + 5
We need to make sure that the left side of the equation is equal to the right side of the equation. That's how pattern matching works. Let's take a look at a bit more complex example with lists (something like arrays):
[a, b, c] = [1, 2, 3]
Here elixir is gonna make sure that the left side matches the right side by binding
3. If that was not impressive enough let's take a look at this:
[a, 2, c] = [5, 2, 6] # ok [z, 2, y] = [6, 7, 9] # throws an error that the right side does not match
The first pattern match works because Elixir goes in and figures out that on the second index of the list value is 2 on the left and on the right and it binds the rest with other values to make the pattern match pass. So
a will be
c will be
For the second pattern match it fails because left side has value
2 as the second position in a list and right side has
7. This is really powerful.
One of the reasons why this is so cool is that you can use pattern matching when you are assigning things to your functions and whole bunch of other existing stuff that I will hopefully blog later on about.
That's all people! If you have any feedback or just wanna chat hit me up on the interwebz.