Clojure - Cond Statement


Advertisements

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.

Syntax

Following is the general form of this statement.

cond
(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.

Example

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

(ns clojure.examples.hello
   (:gen-class))

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

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.

Output

The above code produces the following output.

x is 5
clojure_decision_making.htm
Advertisements