Category: Clojure

Clojure: if-let

I have been learning Clojure. I came across the construct if-let, and failed to understand the explanations I found online.

Here is my attempt to make sense of it:

;; (if-let [definition condition] then else):
;; if the value of condition is truthy, then that value is assigned to the definition,
;; and “then” is evaluated.
;; Otherwise the value is NOT assigned to the definition, and “else” is evaluated.

;; Although you can use this structure with booleans,
;; there’s not much point unless you only want to
;; use the resulting boolean if it’s true – as evidenced in the first example below.
;; if-let is mostly useful when checking for nil.

;; In this first example if Clare is old, it outputs “Clare is old”.
;; (the let part of the statement is rather pointless,
;; as the definition old-clare-age is never used).

(def clare-age 47)
(if-let [old-clare-age (> clare-age 100)]
"Clare is old"
"Clare is not old")

;;=> Clare is not old

;; In the next two examples, it only outputs Clare’s age if it is valid (ie not nil)

(def clare-age nil)
(if-let [valid-clare-age clare-age]
(str "Clare has a valid age: " valid-clare-age)
"Clare's age is invalid")

;;=> Clare’s age is invalid

(def clare-age 47)
(if-let [valid-clare-age clare-age]
(str "Clare has a valid age: " valid-clare-age)
"Clare's age is invalid")

;;=> Clare has a valid age: 47