Making Two Things Match

Elixir’s pattern matching shapes everything you program. It’s useful for assigning variables, unpacking values, and making decisions such as which function to invoke. The basis of pattern matching is that it tries to make two things match, and it does something when it fails to do so.

You’ll start to learn about pattern matching with the = operator. This operator raises a MatchError when it fails to match two things, stopping the program execution. Otherwise, when both sides of the operator have a match, the program keeps running. Let’s see how it works in practice, step by step. Open an IEx session and type the following pattern-matching expression:

 iex>​ 1 = 1
 1
 iex>​ 2 = 1
 **​ (MatchError) no match of right ...

Get Learn Functional Programming with 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.