Chapter 12Control Flow

  • if and unless

  • cond (a multiway if)

  • case (a pattern-matching switch)

  • Exceptions

We’re quite a long way into our exploration of Elixir. But so far we haven’t seen many if statements, or anything else that looks like a conventional control-flow statement.

There’s a good reason for that. 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.

Elixir code tries to be declarative, not imperative.

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 ...

Get Programming Elixir 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.