Pattern match values in Elixir

Kyle Gill
InstructorKyle Gill
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years 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.

egghead
egghead
~ an hour ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today