store/[org.clojure/clojure "1.9.0"] clj::clojure.core/cond

Community Documentation



[& clauses] -> Any


Macro on a series of tests followed by exprs. Each test is evaluated one at a time, if a test returns logical true, the corresponding expr is evaluated and returned without evaluating any more tests or exprs.

Most easily understood as a shorthand for flattening chains of deeply nested clj::clojure.core/if forms.


  • (cond) returns nil.
  • Returns nil if no tests returned true
  • It is a common pattern to use the keyword :else as the test on the final clause of a cond form. :else has no special meaning, it is simply a truthy value which clearly communicates that the following clause is the final else branch of the entire cond form. :else should be preferred to the true constant for clarity's sake.


(defmacro cond
  "Takes a set of test/expr pairs. It evaluates each test one at a
  time.  If a test returns logical true, cond evaluates and returns
  the value of the corresponding expr and doesn't evaluate any of the
  other tests or exprs. (cond) returns nil."
  {:added "1.0"}
  [& clauses]
    (when clauses
      (list 'if (first clauses)
            (if (next clauses)
                (second clauses)
                (throw (IllegalArgumentException.
                         "cond requires an even number of forms")))
            (cons 'clojure.core/cond (next (next clauses))))))

Example 1

;; See examples for "if" explaining Clojure's idea of logical true
;; and logical false.

Example 2

(let [grade 85]
    (>= grade 90) "A"
    (>= grade 80) "B"
    (>= grade 70) "C"
    (>= grade 60) "D"
    :else "F"))
;; => "B"

Example 3

(defn pos-neg-or-zero
  "Determines whether or not n is positive, negative, or zero"
    (< n 0) "negative"
    (> n 0) "positive"
    :else "zero"))

(pos-neg-or-zero 5)
;; => "positive"

(pos-neg-or-zero -1)
;; => "negative"

(pos-neg-or-zero 0)
;; => "zero"

Example 4

;; Generates a random number compares it to user input
(let [rnd   (rand-int 10)
      guess (Integer/parseInt (read-line))]
    (= rnd guess) (println "You got my guess right!")
    :else (println "Sorry... guess again!")))

Uses on crossclj