Functions and Pattern Matching

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. 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} = {1, 2}

This means we can perform more complex pattern matching when we call a function. ...

Get Programming Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.