Clojure - Cond Statement

Clojure offers another evaluation statement called the ‘cond’ statement. This statement takes a set of test/expression pairs. It evaluates each test one at a time. If a test returns logical true, ‘cond’ evaluates and returns the value of the corresponding expression and doesn't evaluate any of the other tests or expressions. ‘cond’ returns nil.


Following is the general form of this statement.

(expression evaluation1) statement #1
(expression evaluation2) statement #2
(expression evaluationN) statement #N
:else statement #Default

The general working of this statement is as follows −

  • There are multiple expression evaluation defined and for each there is a statement which gets executed.

  • There is also a default statement, which gets executed if none of the prior values evaluate to be true. This is defined by the :else statement.


Following is an example of the ‘cond’ statement in Clojure.

(ns clojure.examples.hello

;; This program displays Hello World
(defn Example []
   (def x 5)
      (= x 5) (println "x is 5")
      (= x 10)(println "x is 10")
      :else (println "x is not defined")))

In the above example, we are first initializing a variable x to a value of 5. We then have a ‘cond’ statement which evaluates the value of the variable ‘x’. Based on the value of the variable, it will execute the relevant set of statements.


The above code produces the following output.

x is 5
Kickstart Your Career

Get certified by completing the course

Get Started