Clojure if-else Statement

If-else statements are common in programing languages. Clojure does not have an explicit if-else statement. Instead, Clojure's if statement provides a place for an 'else' case. A Clojure if statement would look like this

(if true "that is true" "that is false") 

This statement looks at the first true. If it is not false or nil then it chooses the first quote "that is true". If not true, then it would run the second quote "that is false".

Note that in Clojure, there are only two values that are false: false and nil. all other values, including (), 0, "" etc. are considered true.

If the second 'else' option is left out, then the function returns nil. The following returns nil:

(if false "this is true")

The following returns 9:

(if nil 7 9)

The if statement in Clojure provides an else statement.

What if you need to check multiple if statements? The following will let you see if A is true, and if A is true if B is also true:

(defn func [] (if a (if b AandB justA) notAnotB))

What if you need multiple if-else-if statements?

This can be done in a number of ways. One common way of writing if-else-if statements in Clojure looks like this:

(defn func [a] (cond (>= a 9) "a is at least 9" (>= a 2) "a is at least 2" :default "a is less than 2" ) )

The cold statement will evaluate each test, and return the value of the first true corresponding expression. Once a true expression is met, the rest of the tests are ignored.

In the last line, the :default keyword is not special in any way. It can be names :else, or :anything or :last. It is just a keyword. This keyword evaluates to true, so it is always run. If no true statements are found, then cold returns nil.

This is a nice equivalent way of having if-else statements in Clojure. `