Skip to content

clojure.core/cond

View this page on ClojureDocs

Type: macro Added: Clojure 1.0 Examples: 9 Runnable: 5
([& clauses])

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.

Examples

by dpritchett on
by bhenry on
by jafingerhut on
by Omer on . May have evaluation errors.
by mhmdsalem1993 on . May have evaluation errors.
by RobinNagpal on . May have evaluation errors.
by chrismurrph on
by berczeck on
by digash on . May have evaluation errors.

Note by blais

We should add a comment in the docstring for the final usage of :else.

Note by kimtg

:else is not special. Any keyword will do.

Note by seltzer1717

Actually any non-nil or true will work. I prefer to use :default. :else implies truthiness in evaluation rather what it really is which is a 'default' value.

Note by yubrshen

It seems the documentation is not accurate. From my experiment, it seems the function decscription should be like the following:

Takes a set of test/expr pairs. It evaluates each test one at a time.
If a test returns logical true, cond evaluates the corresponding expr and continue to evaluate the next test/expr, until a test fails or no more pair of test(:else)/expr to evaluate, and returns the last evaluation value of the expr that its corresponding test evaluated to truthy. If there is no test evaluated to truthy, return the evaluation of :else clause. If there is no :else clause return nil.

The above description can be supported by the following example:

(defn pos-neg-or-zero
  "Determines whether or not n is positive, negative, or zero"
  [n]
  (cond
    (odd? n) "odd"
    (even? n) "even"
    (< n 0) "negitive"
    (< 0 n) "positive"
    :else "zero"))

(odd? 3)                                ; => true
(pos-neg-or-zero 3)                     ;=> "positive"
(even? 0)                               ; => true
(pos-neg-or-zero 0)                     ;=> "zero"
(even? 4)                               ; => true
(pos-neg-or-zero 4)                     ;=> "positive"



### Note by maruks

yubrshen,   

(pos-neg-or-zero 3) => "odd"

### Note by dan-mcdonald

`:else` is just a convention. It works because

=> (boolean :else)
true
In fact anything except for `false` and `nil` will evaluate to `true` (see [boolean](https://clojuredocs.org/clojure.core/boolean)). ## See also --- Content from [the matching ClojureDocs page](https://clojuredocs.org/clojure.core/cond), with authors credited on each contribution.