philipbohun.com

Glojure by Example: Cond and Case

cond walks tests in order and evaluates the expression paired with the first true test. :else is not special syntax. It is a keyword, and keywords are truthy, so it works as a default.

(defn classify [n]
  (cond
    (neg? n) "negative"
    (zero? n) "zero"
    :else "positive"))

(println (classify -1))
(println (classify 0))
(println (classify 2))

case compares a value to constants. It is the counterpart of a Go switch on one value. The last expression is the default, used when nothing matches.

(defn http-text [code]
  (case code
    200 "ok"
    404 "missing"
    500 "error"
    "other"))

(println (http-text 200))
(println (http-text 404))
(println (http-text 302))

case matches constants. cond matches tests.

$ glj cond-and-case.glj
negative
zero
positive
ok
missing
other

Next example: Loop and Recur.