O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required