Pattern matching is a powerful feature of most Functional Programming languages and allows for a huge improvement in readability. At it’s core, pattern match in Elixir relies on the match operator, the = sign. It tries to match the right hand side with the left hand side.
What difference would this have with the == or the === sign that many other languages have?
The match operator allows you to bind variables in addition to checking for a match. Let’s understand this through an example
|
|
Whenever a variable is present on the LHS of a match expression, the value of the expression will be assigned into the variable. In the above example, it will give a successful match on any name which has the first_name value as smith
and it will bind the last_name (“john”) in the last_name
variable. If the first_name
does not match smith
, it will raise a MatchError.
Pattern Match in Function Parameters
Let’s start with an example
|
|
The above example has three implementations defined for print
The overloaded print function will start pattern matching on the arguments with each definition until it finds a match or it would raise a FunctionClauseError
Functions are matched for parameters from top to bottom in the order of definition
Looking at a more complicated example,
|
|
Here the HTML can be transformed to add an italics/bold/strikethrough surrounding it, by changing the way we call transform with the second argument.
You could extract variables inside different types such as tuples, maps and lists using pattern matching in function parameters as well
|
|
Cleaner flows with Pattern Matching
Here is an example for the merge function in Merge Sort, which merges two already sorted arrays. Note how the pattern match in the function arguments combined with the |
operator improves readability.
|
|
Doing more with Guards
Guard clauses restrict the the parameters when pattern matching in functions. Consider a function to check whether the elements in a given list doubles with every element.
|
|
In addition to matching on the function parameters, when x==2*y
should also be true for the function clause to match.
Consider the following example for checking of valid parantheses.
The <<"(", rest::binary>>
format allows for us to pattern match on strings, where the end of the string is allowed to be of variable length and is stored in rest
.
|
|
All in all, pattern matching is a very useful feature enhancing the readability.