comp & partial in Clojure
Weather station readings converted by functions built with comp and partial.
;; comp glues functions right to left: the rightmost one runs first
(def celsius->f #(+ 32 (* 1.8 %)))
(def tenths #(/ (Math/round (* 10.0 %)) 10.0))
(def station-reading (comp tenths celsius->f))
(println (station-reading 21.5) (station-reading -3.0))
;; partial pre-fills the leftmost arguments and returns a new fn
(def scale-by (partial * 100))
(def prefix (partial str "station "))
(println (scale-by 0.42) (prefix "KB7"))
(def readings [21.5 -3.0 14.25 30.0])
;; both compose cleanly with map, which is where they earn their keep
(println (map station-reading readings))
(println (map (comp prefix str) [1 2 3]))
(println (map (partial max 0) [-4 7 -1 12]))
How it works
(comp tenths celsius->f)runscelsius->ffirst and rounds what comes back.(partial * 100)and(partial str "station ")pre-fill the leftmost arguments.- Both go straight into
map, as in(map (comp prefix str) [1 2 3])and(map (partial max 0) [-4 7 -1 12]).
Keywords and builtins used here
compdefmapmaxpartialprefixprintlnstr
The run, in numbers
- Lines
- 17
- Characters to type
- 666
- Tokens
- 134
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 115 seconds.
Step 3 of 3 in Seq toolkit, step 18 of 27 in Language basics.