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 many imperative languages.

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

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

3.1 Pattern matching

As mentioned in chapter 2, the = operator isn’t an assignment. In the expression a = 1, we bind the variable a 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