What is the cond statement in Clojure?

The cond statement

cond is a control statement in Clojure, which means that it controls the flow of the code execution. We can consider it a switch statement; although, more than one expression passes to the cond statement.

If any of the expressions returns true, it executes the statement attached to it. If the expression returns false, it moves to the next statement. The else statement executes when all the expressions evaluate false.

Syntax

cond
(exp eval1) statement #1
(exp eval2) statement #2
(exp evalN) statement #N
:else statement #Default
Syntax for the cond statement

Example

The cond statement is a conditional statement that evaluates multiple expressions, and breaks out once any of the expressions is true . Even if the first expression evaluates true, it executes the attached statement. Let's see an example:

(ns clojure.examples.hello
(:gen-class))
(defn func []
(def y 8)
(cond
(= y 12) (println "y is 12")
(= y 9)(println "y is 9")
:else (println "y is not 9 or 12")))
(func)

Code explanation

Line 3: We define the func function.

Line 4: We define the variable we want to test, y, and initialize it to equal 8.

Line 5: We use the cond statement.

Line 6: We check if y equals 12. This is not true because y equals 8.

Line 7: We check if y equals 9. This is not true because y equals 8.

Line 8: We use the else statement, which executes when all the expressions evaluate false. Since y is not 12 or 9, the else statement executes.

Line 9: Finally, we call the func function.

Free Resources