Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

clojure
cond statement
community creator
cond

What is the cond statement in Clojure?

Chinweuba Elijah Azubuike

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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)
An example of the cond statement

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.

RELATED TAGS

clojure
cond statement
community creator
cond

CONTRIBUTOR

Chinweuba Elijah Azubuike

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring