{:check ["true"], :rank ["if" "cond"]}
Clojure provides the following form for if-else
:
(if <cond>
<if-expr>
<else-expr>)
Note:
<if-expr>
must be a single expression.<else-expr>
must be a single expression.; Convert age to category
(def age 65)
(if (>= age 65)
"Senior"
"Not Senior")
; A cleaner way
(let [age 65]
(if (>= age 65)
"Senior"
"Not Senior"))
; An even better way - make a function
(defn age->str [age]
(if (>= age 65)
"Senior"
"Not Senior"))
(println (age->str 60))
(println (age->str 70))
;
What if we want to do:
(if <cond>
<expr1>
<expr2>
;; else
<expr3>
<expr4>)
You need to use the (do ...)
form.
; Do accepts multiple expressions and evaluates all of them.
; But only the last expression's value is kept.
(do "Hello"
"World"
(str "Albert" "Einstein")
(+ 1 1)
(+ 1 2 3))
; A good usage of `do` is to bundle
; println expressions in `if`
(if (>= age 65)
(do (println "age" age ">=65")
"Senior")
(do (println "age" age "<65")
"Not Senior"))
(if (>= age 65) "Senior")
(if (>= age 90) "Old")
(and ...)
(or ...)
(not ...)
; 65 <= age <= 70
(and (>= age 65) (<= age 70))
; Senior or Child
(or (>= age 65) (<= age 12))
; Not senior
(not (>= age 65))
cond
: A Better if
¶(cond <condition> <expression>
<condition> <expression>
...)
; A pretty bad implementation
(defn age->category
[age]
(if (<= age 12)
"Child"
(if (<= age 21)
"Teen"
(if (< age 65)
"Adult"
"Senior"))))
(println (age->category 23))
(println (age->category 31))
(println (age->category 5))
(println (age->category 100))
;
; Cond to the rescue
(defn age->category
[age]
(cond
(<= age 12) "Child"
(<= age 21) "Teen"
(< age 65) "Adult"
:else "Senior"))
(println (age->category 23))
(println (age->category 31))
(println (age->category 5))
(println (age->category 100))
;