3 Control flow

 

This chapter covers

  • Understanding pattern matching
  • Working with multiclause functions
  • Using conditional expressions
  • Working with loops

Now that you’re familiar with Elixir’s basic building blocks, it’s time to look at some typical low-level idioms of the language. In this chapter, we’ll deal with conditionals and loops. As you’ll see, these work differently than in most modern, imperative languages.

Classical conditional constructs such as if and case are often replaced with multiclause functions, and there are no classical loop statements such as while. But you can still solve problems of arbitrary complexity in Elixir, and the resulting code is no more complicated than a typical OO solution.

All this may sound a bit radical, which is why conditionals and loops receive a detailed treatment in this chapter. But before we start discussing branching and looping, you need to learn about the important underlying supporting mechanism: pattern matching.

3.1 Pattern matching

As mentioned in chapter 2, the = operator isn’t an assignment. Instead, when I wrote a = 1, I said variable a was bound to the value 1. The operator = is called the match operator, and the assignment-like expression is an example of pattern matching.

3.1.1 The match operator

3.1.2 Matching tuples

3.1.3 Matching constants

3.1.4 Variables in patterns

3.1.5 Matching lists

3.1.6 Matching maps

3.1.7 Matching bitstrings and binaries

3.1.8 Compound matches

3.1.9 General behavior

3.2 Matching with functions

3.2.1 Multiclause functions

3.2.2 Guards

3.2.3 Multiclause lambdas

3.3 Conditionals

3.3.1 Branching with multiclause functions

3.3.2 Classical branching constructs

3.3.3 The with special form

3.4 Loops and iterations

3.4.2 Tail function calls