Do and When

One wrinkle with Clojure’s if is that you are limited to one expression for the truthy leg and one for the falsy leg. But what happens if you want to do several things when the condition is truthy? Or several when the condition is falsy? The key word here is do because that is what Clojure calls its group a bunch of expressions into a single expression construct. Thus, this:

 (do
  (println ​"This is four expressions."​)
  (println ​"All grouped together as one"​)
  (println ​"That prints some stuff and then evaluates to 44"​)
  44)

is a single expression that returns 44. Armed with do, we can flesh out a simple if with multipart true and false legs:

 (​defn​ shipping-charge[preferred-customer order-amount]
  (​if​ preferred-customer ...

Get Getting Clojure 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.