Clojure - If/do Expression


Advertisements

The ‘if-do’ expression in Clojure is used to allow multiple expressions to be executed for each branch of the ‘if’ statement. We have seen in the classic ‘if’ statement in Clojure that you can just have two statements, one which is executed for the true part and the other which is for the false part. But the ‘if-do’ expression allows you to use multiple expressions. Following is the general form of the ‘if-do’ expression.

Syntax

if(condition) (
   statement #1
   statement #1.1
)

(
   statement #2
   statement #2.1
)

Example

Following is an example of a ‘for if-do’ statement.

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

;; This program displays Hello World
(defn Example [] (
   if (= 2 2)
      (do(println "Both the values are equal")
         (println "true"))
      (do(println "Both the values are not equal")
         (println "false"))))
(Example)

In the above example, the ‘if’ condition is used to evaluate whether the values of 2 and 2 are equal. If they are, then it will print the value of “Values are equal” and in addition we are printing the value of “true”, else it will print the value of “Values are not equal” and the value of “false”.

Output

The above code produces the following output.

Both the values are equal
true
clojure_decision_making.htm
Advertisements