typestar

if, when & cond in Clojure

Tide gauge readings routed through if, when and cond.

;; if takes a test, a then branch, and an optional else branch
(defn tide-label [meters]
  (if (> meters 2.0) "high" "low"))

;; when is the one-branch case; nil comes back when the test fails
(defn flood-watch [meters]
  (when (> meters 3.0) (str "flood watch at " meters " m")))

;; cond walks pairs in order and :else is just a truthy keyword
(defn advice [meters]
  (cond
    (> meters 3.0) "stay ashore"
    (> meters 2.0) "moor the skiff"
    :else "normal range"))

;; if returns a value, so it can feed a def directly
(def gauge-note (if (> 3.4 0.0) "gauge online" "gauge offline"))
(println gauge-note (tide-label 2.6) (advice 3.2) (flood-watch 3.4))

How it works

  1. tide-label uses the three-argument if: a test, a then branch, and an else branch.
  2. flood-watch shows when as the one-branch form, which yields nil when the test fails.
  3. advice walks cond pairs in order down to :else, and gauge-note stores an if result in a def.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
641
Tokens
96
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 77 seconds.

Type this snippet

Step 1 of 3 in Flow & truthiness, step 10 of 27 in Language basics.

← Previous Next →