How to use cases in Clojure
The conditional branching in Clojure can be performed using the case multi-way branch statement. Typically, it is used to cope with multiple and distinct conditions.
The syntax of the case statement is given below:
case expression/variable
value1 statement1
value2 statement2
valueN statementN
statement ; default
It works as follows:
The given
expressionis evaluated into a single value (a.k.a., the expression's value).The expression's value is compared against each value passed in the
casestatement. When matching, the subsequent statement gets executed.If the expression's value did not match any of the case values, then the default
statementis executed, the one with no value.When no default expression is provided, and the expression's value did not match any case value, an error
IllegalArgumentExceptionis thrown.
The following diagram illustrates the flow of the case statement:
Code example
The following example demonstrates the use of the case statement:
(defn CaseExample [](def agelimit 18)(case agelimit1 (println "Baby")3 (println "Toddler")5 (println "Preschooler")10 (println "Gradeschooler")18 (println "Teen")(println "Adult")));;Call the function(CaseExample)
Code explanation
Let's now explain the above code snippet:
Line 1: We define a private function called
CaseExample.Line 2: We initialize the variable
ageLimitto18.Lines 3–9: We declare a case clause that evaluates the
agelimitvariable and specify a default statement that gets executed if theagelimitdid not match any of the designated values.Line 12: We invoke the
CaseExamplefunction.
Free Resources