Vector destructuring in Clojure
Pulls trail waypoints and a coordinate pair apart by position inside let.
;; Destructuring a vector binds names to positions from left to
;; right, and & gathers everything still unnamed into a sequence.
(def waypoints [:trailhead :bridge :ridge :summit])
(let [[start next-stop & later] waypoints]
(println (format "start %s, then %s, %d to go"
(name start) (name next-stop) (count later))))
;; :as keeps a name for the whole vector while the parts stay bound.
(let [[lat lon :as fix] [45.52 -122.68]]
(println (format "%.2f/%.2f from %d parts" lat lon (count fix))))
;; Nesting works at any depth, and _ marks a slot you do not need.
(def leg [[45.52 -122.68] [47.61 -122.33]])
(let [[[from-lat _] [to-lat _]] leg]
(println (format "north by %.2f degrees" (- to-lat from-lat))))
How it works
(let [[start next-stop & later] waypoints]names the first two elements and collects everything after them intolater.- The binding
[lat lon :as fix]splits a coordinate pair whilefixstill refers to the whole vector. [[from-lat _] [to-lat _]]reaches into a vector of vectors, and_marks the longitudes this code ignores.
Keywords and builtins used here
countdefformatletnameprintln
The run, in numbers
- Lines
- 16
- Characters to type
- 709
- Tokens
- 115
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 99 seconds.
Step 1 of 3 in Destructuring, step 19 of 27 in Language basics.