Pattern Matching is Undoubtedely the most enticing feature of Elixir (and many other Programming Languages that supports it). In this blog I will try to explain how Elixir does Pattern Matching using example codes. There are essentially 3 different ways to do Pattern Matching in Elixir -
Equal (=) symbol in most programming language is considered as assigning a value to a variable. In Elixir, this is called Pattern Matching Operator instead.
In Python you can write
This means we are assigning the value 5 to the variable x
You can write the same expression in Elixir, but the meaning is completely different. In Elixir this means we are matching the left-hand side i.e; x to the right-hand side i.e; 5. Following are the matching rules-
Because of this the following statement will also compile in Elxir
But this will fail because y was never set
Note that variables can be re-assigned to another value
You can also match complex data structures like Tuples, Map, List etc.
Notice that you can destructure a list into it's head and tail using Pattern Matching.
The following will fail, because 2 and 3 does not match 200 and 300 respectively.
Pattern matching are mostly useful in the context of defining functions. Let's say you want to define a function that takes address data as input and format that into string. Let's say your application represents address in two different ways-
You can implement this in the following way-
You can define two functions, one taking a map and one taking tuple, and it just works.
So far I have discussed two ways of pattern matching in Elixir, 1. By = operator, 2. In function arguments. But there is a third way of doing pattern matching as well : The case statements. Similar to C, C++ and Javascript switch-case statement (but more powerful), one can do pattern matching in case statements
Let's say you want to define a function in Elixir to return the first element from the list, if non-empty, and a default value if empty You can do so using case statement
First, the input list lst is matched against [], if matched it returns the default value, if not then lst is matched against the next pattern [x | xs], and now it will surely match because the list lst is non-empty, it will now return the first element x and we are done.
Thank you very much if you are still reading, and with this I will wrap this up. Happy Coding and Keep Learning 😄