O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

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

Pattern Matching

This is where pattern matching comes in. The parameter list of the first function clause is just the empty list. When you call sum, this clause will match if and only if you call it with an empty list. If it does match, the function returns 0.

The second clause has a complicated parameter list: [head|tail]. This pattern matches a list (the square brackets tell us that). The list must have a first element (the head) and a tail (the remainder of the list). If the list we pass in has only one element, the head will be set to that element, and the tail will be the empty list.

So let’s call MyList.sum with the argument [1,2,3]. Elixir looks for the first clause whose pattern matches the argument. The first clause doesn’t match—the ...

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