Skip to content

Instantly share code, notes, and snippets.

@fay-jai
Created November 9, 2018 06:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fay-jai/b2ac3b4e5579dacef129e99e126bc12e to your computer and use it in GitHub Desktop.
Save fay-jai/b2ac3b4e5579dacef129e99e126bc12e to your computer and use it in GitHub Desktop.
Programming Elixir Chapter 2 - Pattern Matching
# Pattern Matching in Elixir
# Basic pattern matching examples
a = 1 # In order for this to match, 'a' must be bound to the value of 1
1 = a # Since a is already bound to the value of 1, this looks more like 1 = 1. And in that case, the match will be successful.
2 = a # Since a is already bound to the value of 1, this looks more like 2 = 1. This match will fail since we can't make both sides match in value.
# Pattern matching examples with lists
list = [1, 2, 3] # In order for the left and right hand sides to match in both structure and value, the left hand side 'list' must be bound to the value [1, 2, 3]
[a, b, c] = [1, 2, 3] # In order for the left and right hand sides to match in both structure and value, Elixir can bind 1 to a, 2 to b, and 3 to c.
[a, b] = [1, 2, 3] # This match will fail because there's no way to match both sides in structure and value
# Special cases
[a, a] = [1, 1] # During a given match, Elixir will perform pattern matching from left to right. Also once Elixir has bound a variable to a value in a given match, that variable will be bound to that value for the entirety of the given match. In this example, what this means is that when the 1st 'a' on the left is encountered, it will be bound to 1 and when the 2nd 'a' is encountered, the value of a is already 1 and the match will look more like 1 = 1. Hence this match will be successful.
[a, a] = [1, 2] # From the above example, we should know that the 1st 'a' will be bound to 1, and when the 2nd 'a' is encountered, the match is more like 2 = 1. Hence this match will fail.
a = 1
[^a, b] = [1, 2] # The ^ operator is called the pin operator because when it is encountered, it pins and uses the current value of the variable to perform the match. In other words, this match is more like [1, b] = [1, 2] and this will match successfully when b is bound to 2.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment