Matthew Boston

Understanding Clojure: cond and condp

January 27, 2016

Key takeaway: Reach for condp when every branch of a cond calls the same predicate on the same value.

Use cond when each branch has its own test. Use condp when every branch applies the same predicate and only the value changes.

cond checks predicates in order and takes :else as a default:

(cond
  (> 0 (:amount account)) "Your balance is negative"
  (< 0 (:amount account)) "Your balance is positive"
  :else "Your balance is zero")

condp takes one predicate and switches on the result. For a default, leave out :else and put the bare result expression last:

(condp < (:amount account)
  10000 "top tier dividend"
  5000 "second tier dividend"
  1000 "first tier dividend"
  "no dividend")

You can also pass your own predicate:

(defn describe [amount]
  (cond
    (> 0 amount) :negative
    (< 0 amount) :positive
    :else :zero))

(defn compare [descriptor amount]
  (= descriptor (describe amount)))

(condp compare (:amount account)
  :negative "Your balance is negative"
  :positive "Your balance is positive"
  :zero "Your balance is zero")

The predicate must take exactly two arguments and return a true or false result. condp calls it as (compare :negative (:amount account)), then (compare :positive (:amount account)), and so on until one matches.