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
tide-labeluses the three-argumentif: a test, a then branch, and an else branch.flood-watchshowswhenas the one-branch form, which yields nil when the test fails.advicewalkscondpairs in order down to:else, andgauge-notestores anifresult in adef.
Keywords and builtins used here
adviceconddefdefnifprintlnstrwhen
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.
Step 1 of 3 in Flow & truthiness, step 10 of 27 in Language basics.