Pattern match in conditions and function parameters 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

Some common uses for pattern matching in Elixir include checking conditions and passing parameters into functions. It's useful for pulling out only specific variables from collections of data.

Additional resources:

Kyle Gill: [0:00] Pattern matching can also be used in condition checks or matching variables and function parameters.

[0:05] Inside this HelloWorld module and with this hello() function, you can refactor the function to pattern match a name from a map passed into it. Change the parameter to a map with the percent sign and add the new variable name to be used in place of where value would be.

[0:19] With a user who has a name attribute, like this user with the name Kyle, the value name will be matched off with the map and assigned to username. Make sure to recompile code or run a new Elixir Shell to make sure your changes have taken effect for your module.

[0:34] Then, calling hello and passing in the user, it matches the map from the function declaration name: username with a map you defined of id: 1 named Kyle for the user. The username value is matched with the data on the right assigning Kyle to the username variable.

[0:54] For context, this method of pattern matching maps in function parameters is commonly used in the Phoenix framework. You can also use pattern matching on a condition in a case statement to easily pick variables out of a data structure and run a specific case.

[1:07] With this case of a tuple {1, 2, 3}, it won't match the first case, but it would match the second, as well as binding c to the value 3. The third case wouldn't be reached, but it would match. The underscore is special and is used for binding values you don't care about.

[1:22] When executed, this code will print out the second message.

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