typestar

Threading macros in Clojure

One elevation pipeline written nested, then with ->>, plus -> over a map.

(def elevations [820 1450 610 1980 1230])

;; nested calls read inside out: the last thing written happens first
(println (apply + (take 3 (sort > (filter #(> % 700) elevations)))))

;; ->> threads the value into the last slot, which suits seq functions
(println (->> elevations
              (filter #(> % 700))
              (sort >)
              (take 3)
              (apply +)))

;; -> threads into the first slot, which suits maps and assoc/update
(def trail {:name "ridge loop" :miles 6.2})
(println (-> trail
             (assoc :gain 1450)
             (update :miles + 0.8)
             (assoc :steep? true)))

How it works

  1. The nested (apply + (take 3 (sort > (filter #(> % 700) elevations)))) has to be read inside out.
  2. ->> threads the value into the last slot, so (filter #(> % 700)) and (take 3) line up in reading order.
  3. -> threads into the first slot, letting (assoc :gain 1450) and (update :miles + 0.8) walk the trail map.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
525
Tokens
100
Three-star pace
70 tpm

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

Type this snippet

Step 3 of 3 in Sequences, step 15 of 27 in Language basics.

← Previous Next →