Primer on Pattern Matching in Elixir

I’ve just started exploring Elixir and realised we can write succinct and readable code in it, thanks to features like pattern matching, piping etc.

Through this article, I’d like to share my understanding of Pattern Matching in Elixir and hope this helps others.

Prerequisites

  • Familiarity with one or more general purpose programming languages like C, Java, Python and understanding of data structures like list, map.
  • Familiarity with Elixir is not required to grasp the ideas behind pattern matching explained here.

Following is the structure of a Pattern Match in Elixir:

‘=’ in Elixir is a match operator and not an assignment operator, unlike most of the other programming languages.

Let’s build our pattern matching fundamentals using Elixir primitives.

On Primitives

Elixir has common primitive data types like strings, integers, floats etc.

We can visualise pattern matching as a process where values(RHS) are thrown at a wall after pasting double sided tape patches(LHS) on the wall to catch hold(bind) of a subset(or the entire value) of thrown values.

The same tapes(variables) can be reused to hold another value of a different data type — which is called rebinding.

When a variable is used for the first time, it’s unbounded and it can only be on the LHS, to be bounded.

Now that the fundamentals of pattern matching are clear, let’s see how it works on various data structures in Elixir.

On Lists

Tuples in Elixir are created using curly braces and are stored contiguously in memory. The behaviour of pattern matching on tuples is similar to lists.

On Maps

Pattern matching on Elixir structs works similar to maps.

I’ll cover pin operator, guards, using pattern matching in functions and cases in another article.

References

All Things Tech @StockGro | EX-Glance | EX-D E Shaw