Dealing with Multiple Conditions

Technically, no matter how complicated the decision you need to make, the plain old if is all you ever need. Choosing between three alternatives? Just nest a couple of ifs. Say, for example, our shipping charges were free to preferred customers and otherwise $5 for orders under $50, $10 for orders between $50 and $100, and 10% of the purchase price for bigger orders, we could write something like this:

 (​defn​ shipping-charge [preferred-customer order-amount]
  (​if​ preferred-customer
  0.0
  (​if​ (< order-amount 50.0)
  5.0
  (​if​ (< order-amount 100.0)
  10.0
  (* 0.1 order-amount)))))

Have another alternative? Then just nest another if—and at some point drive yourself crazy. While your CPU may be fine ...

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.