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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access