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 expression
is evaluated into a single value (a.k.a., the expression's value).
The expression's value is compared against each value passed in the case
statement. When matching, the subsequent statement gets executed.
If the expression's value did not match any of the case values, then the default statement
is 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 IllegalArgumentException
is thrown.
The following diagram illustrates the flow of the case
statement:
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)
Let's now explain the above code snippet:
Line 1: We define a private function called CaseExample
.
Line 2: We initialize the variable ageLimit
to 18
.
Lines 3–9: We declare a case clause that evaluates the agelimit
variable and specify a default statement that gets executed if the agelimit
did not match any of the designated values.
Line 12: We invoke the CaseExample
function.
Free Resources