Pattern Matching is one of the fundamental concepts that we need to master while learning Elixir. If you are new to functional programming it may be a completely new idea for you. In majority of the programming languages out there, = is called the assignment operator and as its name implies it is used for assigning a value to a variable. But in Elixir, = is called the match operator, which performs the pattern matching operation between its operands - a pattern on its left side and an expression on its right.

In an IEx shell, type the following code

user = "John Doe"

Here the pattern is user which is a variable name and expression is the string “John Doe”. If the pattern is a variable name like this, then Elixir will simply bind the value of the expression to the variable. So after this statement is executed, the value “John Doe” will be bound to the variable user. So it just feels like an assignment statement for us.

But the pattern on the left side of = does not need to be a variable name. It can be any basic data type value or any other data structure such as list, map, tuple etc.

Consider the following code

"John Doe" = user

Here the pattern is the string “John Doe”. Since the expression user also has the same value, they will be matched successfully. This is just a trivial example for you to understand the basic concept. Let’s look into some useful stuff with pattern matching.

Pattern matching allows us to easily access contents of complex data structures. Consider the following example

user = %{"first_name"=>"John","last_name"=>"Doe","age"=>20}
%{"first_name"=>first_name,"age"=>age} = user

Here user is a map and we want to extract first_name and age from it. After executing the above statements the variable first_name will be bound to the value “John” and the variable age will be bound to 20. (When matching maps, the pattern does not need to have all the keys in the expression)

We can use the ^ pin operator, if we want to pattern match against the value of a variable.

age = 20
^age = 21

The above code will raise an error, since the value of age is already bound to the value 20. Since we are using the pin operator in front of the variable name, the value of the variable will not be rebound. (Note that we can use the pin operator only with a variable which is already bound to a value)