Lesson 5 of 16
Pattern Matching
The Match Operator
In Elixir, = is the match operator, not just assignment. It binds variables on the left to values on the right.
x = 10
IO.puts(x) # 10
Tuple Destructuring
You can match tuples to extract values:
{a, b} = {10, 20}
IO.puts(a) # 10
IO.puts(b) # 20
List Destructuring
Match list head and tail with [head | tail]:
[first | rest] = [1, 2, 3, 4]
IO.puts(first) # 1
IO.puts(length(rest)) # 3
Your Turn
- Match
{a, b} = {10, 20}and print both values - Match
[first | rest] = [1, 2, 3, 4]and printfirstandlength(rest)
JS Transpiler loading...
Loading...
Click "Run" to execute your code.