Pattern match in conditions and function parameters in Elixir

Kyle Gill
InstructorKyle Gill

Share this video with your friends

Send Tweet
Published 2 years ago
Updated a year 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.