We cover:

  • if and unless
  • cond (a multiway if)
  • case (a pattern-matching switch)
  • Exceptions

Chapter 12Control Flow

Elixir code tries to be declarative, not imperative.

In Elixir we write lots of small functions, and a combination of guard clauses and pattern matching of parameters replaces most of the control flow seen in other languages.

However, Elixir does have a small set of control-flow constructs. The reason I’ve waited so long to introduce them is that I want you to try not to use them much. You definitely will, and should, drop the occasional if or case into your code. But before you do, consider more functional alternatives. The benefit will become obvious as you write more code—functions written without explicit control flow tend to be shorter ...

Get Programming Elixir 1.2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.