Pattern matching

When we were describing Elixir's data types, we used the = operator to bind a value of a certain type to a variable. We didn't stop there to explain what was actually going on, as the syntax is very similar to most dynamic programming languages. In fact, it is so similar that, at first glance, we assume it works the same way.

If you don't have a functional programming background, your first instinct would be to call the = operator, the assignment operator. However, in Elixir, it is called the match operator. Let's see the reason for this difference in nomenclature with some examples:

iex> x = 33iex> x * 39iex> 3 = x3iex> 2 = x** (MatchError) no match of right hand side value: 3
We've seen our first exception being raised ...

Get Mastering Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.