When we call sum.(2,3), it’s easy to assume we simply assign 2 to the parameter a and 3 to b. But that word, assign, should ring some bells. Elixir doesn’t have assignment. Instead it tries to match values to patterns. (We came across this when we looked at pattern matching and assignment.)
If we write
| a = 2 |
then Elixir makes the pattern match by binding a to the value 2. And that’s exactly what happens when our sum function gets called. If we pass 2 and 3 as arguments, and Elixir tries to match these arguments to the parameters a and b (which it does by giving a the value 2 and b the value 3), it’s the same as when we write
| {a, b} = {2, 3} |
This means we can perform more complex pattern matching when we call a function. For example, the following function reverses the order of elements in a two-element tuple:
| iex> swap = fn { a, b } -> { b, a } end |
| #Function<12.17052888 in :erl_eval.expr/5> |
| iex> swap.( { 6, 8 } ) |
| {8, 6} |
We’ll use this pattern-matching capability when we look at functions with multiple implementations in the next section.