Flow Control

Clojure has very few flow control forms. In this section, you will meet if, do, and loop/recur. As it turns out, this is almost all you will ever need.

Branch with if

Clojure’s if evaluates its first argument. If the argument is logically true, it returns the result of evaluating its second argument:

src/examples/exploring.clj
 ​(​defn​ is-small? [number]​
 ​ (​if​ (< number 100) ​"yes"​))​
 ​(is-small? 50)​
 ​-> "yes"​

If the first argument to if is logically false, it returns nil:

 ​(is-small? 50000)​
 ​-> nil​

If you want to define a result for the “else” part of if, add it as a third argument:

src/examples/exploring.clj
 ​(​defn​ is-small? [number]​
 ​ (​if​ (< number 100) ​"yes"​ ​"no"​))​
 ​(is-small? 50000)​
 ​-> "no"​

The when ...

Get Programming Clojure, 2nd Edition 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.