chapter twelve

12 Vectors

 
Thanks to Rachel Bowyer for contributing this chapter.

Clojure’s vector is one of the standout features of the language: performant, immutable and with a convenient literal syntax. Back in 2008 when Clojure launched there was nothing else quite like it; and it set Clojure apart from earlier LISPs. Since then other functional languages such as Scala and Haskell have added their own immutable vector.

Clojure’s vector stores elements sequentially, indexed by zero based integers. It provides efficient index based read and write, and also append. It supports efficient delete from the tail of the vector (with pop), but not from other locations (for which the best workaround is to use “subvec”).

The literal syntax for a vector consists of merely enclosing a space separated list of the elements within a pair of square brackets.

[:a :b :c]
;; => [:a :b :c]

As well as being a data structure, a vector is also a function that looks up a value. It takes one argument, the zero based index, and if it is out of range then an IndexOutOfBoundsException is thrown.

(ifn? [])       #1
;; true

([:a :b :c] 2)  #2
;; => :c

([:a :b :c] 3)  #3
;; IndexOutOfBoundsException   clojure.lang.PersistentVector.arrayFor (PersistentVector.java:158)

Functions that operate on vectors

12.1  vector

12.2  vec

12.3  peek and pop

12.4  vector-of

12.5  mapv

12.6  filterv

12.7  subvec