Vector operations in Clojure
Builds a ferry route as a vector, then reads it by index, count, and slice.
;; a vector literal is written with square brackets
(def legs ["quarry" "ridge" "hollow" "ferry"])
;; conj adds to the end of a vector and hands back a new one
(def route (conj legs "depot"))
;; nth reads by position, and a vector is itself a function of its index
(println (nth route 0) "then" (route 1))
(println "legs:" (count route))
;; subvec takes a slice that shares the original storage
(println "middle:" (subvec route 1 3))
;; vectors compare by value, so an equal slice is equal
(println (= ["quarry" "ridge"] (subvec route 0 2)))
How it works
(conj legs "depot")returns a new vector with the stop added at the end.(nth route 0)and(route 1)both read by position, since a vector is a function of its index.(subvec route 1 3)takes a slice, and=shows that vectors compare by value.
Keywords and builtins used here
conjcountdefnthprintlnroutesubvec
The run, in numbers
- Lines
- 15
- Characters to type
- 545
- Tokens
- 71
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 57 seconds.
Step 1 of 3 in Collections, step 4 of 27 in Language basics.