Conditionals
Prerequisites: Truthiness, nil, and booleans
if
(def temperature 31)
(println (if (> temperature 30) "Hot" "Not hot"))
(if (> temperature 30)
(do
(println "Stay hydrated")
(println "Find some shade"))
(println "Enjoy the weather"))
Hot
Stay hydrated
Find some shade
(if test then else)is an expression: it returns the value of the branch that ran.- Each branch is one form. Use
doto run several forms;doreturns the last one's value. - Without an else branch,
ifreturnsnilwhen the test is falsy.
when
(def items ["apple"])
(when (seq items)
(println "You have" (count items) "item(s)")
(println "First:" (first items)))
(when-not (seq [])
(println "The list is empty"))
You have 1 item(s)
First: apple
The list is empty
when is if with no else and an implicit do — use it for side
effects that should happen only sometimes.
cond
(defn describe [n]
(cond
(neg? n) "negative"
(zero? n) "zero"
(< n 10) "small"
:else "large"))
(println (map describe [-5 0 7 250]))
(negative zero small large)
cond checks test/result pairs in order and returns the first match.
:else is just a keyword — always truthy — used as the catch-all.
case
(defn http-status [code]
(case code
200 "OK"
404 "Not Found"
(500 502 503) "Server Error"
"Unknown"))
(println (map http-status [200 404 503 418]))
(OK Not Found Server Error Unknown)
case compares against constants (numbers, strings, keywords) in
constant time. A list of constants matches any of them, and the final
lone value is the default — without one, an unmatched value throws an
exception.
Practice
Write fizzbuzz that returns "FizzBuzz", "Fizz", "Buzz", or the
number, and print the results for 1 to 15.
Show solution
(defn fizzbuzz [n]
(cond
(zero? (mod n 15)) "FizzBuzz"
(zero? (mod n 3)) "Fizz"
(zero? (mod n 5)) "Buzz"
:else n))
(println (map fizzbuzz (range 1 16)))
(1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz)