case & condp in Clojure
Subway line colors chosen by case on literals, crowding levels by condp.
;; case dispatches on literal constants and never evaluates them
(defn line-color [line]
(case line
("A" "C" "E") "blue"
("1" "2" "3") "red"
"G" "light green"
"unknown line"))
;; the trailing expression is the default; without one a miss throws
(println (line-color "C") (line-color "G") (line-color "Q"))
;; condp holds a predicate and a right-hand argument across the clauses
(defn crowding [riders]
(condp <= riders
900 "crush"
500 "heavy"
"light"))
(println (map crowding [1200 640 40]))
How it works
line-colorgroups literals in lists like("A" "C" "E")so several keys share one result.- The trailing
"unknown line"is the default, and without it an unmatched value throws. crowdingusescondp <= riders, so the clause900 "crush"fires when 900 is at or below the count.
Keywords and builtins used here
casecondpdefnmapprintln
The run, in numbers
- Lines
- 19
- Characters to type
- 494
- Tokens
- 73
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 58 seconds.
Step 3 of 3 in Flow & truthiness, step 12 of 27 in Language basics.