Chapter 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 conditional 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.
As mentioned in chapter 2, the = operator isn’t an assignment. Instead, when we wrote a = 1, we 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.