Elixir Pattern Matching

Welcome to a tutorial on Elixir. Here you will learn about Pattern Matching in Elixir.

Pattern matching is a technique inherited from Erlang by Elixir. Pattern matching is a powerful technique that allows the extraction of simpler substructures from complicated data structures like lists, tuples, maps, and many more.

Typically, a match has 2 main parts, a left, and a right side; the right side is a data structure of any kind, while the left side attempts to match the data structure on the right side and bind any variables on the left to the respective substructure on the right. however, if a match is not found, the operator raises an error.

In pattern matching, the simplest match is a lone variable on the left and any data structure on the right, and this variable will match anything. Check out the example below:

x = 12
x = "Hello"
IO.puts(x)

Also, you can place variables inside a structure so that you can capture a substructure. This is shown below.

[var_1, _unused_var, var_2] = [{"First variable"}, 25, "Second variable" ]
IO.puts(var_1)
IO.puts(var_2)

The above will store the values, {"First variable"} in var_1 and "Second variable" in var_2. Also, there is a special _ variable(or variables prefixed with '_') that works exactly like other variables but tells elixir, "Make sure something is here, but I don't care exactly what it is.". For instance, in the previous example, _unused_var was one such variable.

With this technique, we can match more complicated patterns. For instance, if we want to unwrap and get a number in a tuple that is inside a list that itself is in a list. The command can be used.

[_, [_, {a}]] = ["Random string", [:an_atom, {24}]]
IO.puts(a)

Output:

24

From the above, a is bound to 24, and other values are ignored as we are using '_'.

If we use a variable on the right, its value is used, but if you want to use the value of a variable on the left, you'll need to use the pin operator.

Now, suppose you have a variable "a" having a value of 25 and you want to match it with another variable "b" having 25, thus you can enter the code below.

a = 25
b = 25
^a = b

In the above code, the last line matches the current value of a, rather than assigning it to the value of b. In addition, if we have a non-matching set of left and right-hand side, the match operator raises an error. E.g. if we try to match a tuple with a list or a list of size 2 with a list of size 3, we will get an error.