Pattern match values in Elixir

Kyle Gill
InstructorKyle Gill

Share this video with your friends

Send Tweet
Published 2 years ago
Updated a year ago

Elixir uses = as an operator, but rather than assigning values to variables with it, it matches values on the right hand side of the = with the left side. This can be used in simple values, more complex data structures, and powerful condition checking.

Put into simpler terms, pattern matching is Elixir's way of assigning variables.

Additional resources:

Kyle Gill: [0:00] Instead of using an equal sign as an assignment operator, Elixir calls it the match operator. You can see why inside of an Elixir Shell run with iex. The simplest example of pattern matching is with variable assignment like x = 1. After pattern matching x with 1, when you call x, the value of 1 is returned.

[0:20] If you reverse the equation, 1 = x, 1 will still be returned because the values still match. Note however that variables are only assigned on the left-hand side of the equal sign or match operator.

[0:32] Complex data structures can be destructured into variables with pattern matching like a tuple of {a, b} match with the strings of a tuple of the same size {"hello", "world"}, a matching with hello and b matching with world.

[0:48] When sides don't match like with data structures of different sizes or types, Elixir returns a match error like in the case of a tuple x matched with a tuple of size two or a tuple matched with a list. Data structures of the same size and type will match.

[1:06] Specific values can be matched like with a response from a server verifying whether an OK response or an error was returned. Trying a tuple with an atom or symbol :OK and a user matched with :OK in the map of data matches the user variable with the data on the right.

[1:29] As a summary, pattern matching is Elixir's way of assigning variables, which lends itself to many of Elixirs commonly used patterns.