liveBook · Manning

Vector

As explained in Clojure: The Essential Reference

A vector is an ordered, indexed Clojure collection that stores values as sequential elements.

A Clojure vector is an immutable, ordered collection with zero-based indexes. Use one when you need direct access to positions, efficient appends, or removal from the tail. Write a vector by placing its elements in square brackets: `[:a :b :c]`. section 12.1

Common operations preserve the vector's indexed role:

  • `(get [:a :b :c] 2)` and `(nth [:a :b :c] 2)` return `:c`. A vector can itself be called with an index, but an out-of-range index then throws `IndexOutOfBoundsException`. section 12.1 section 12.2
  • `(assoc [:a :b :c] 2 :d)` returns `[:a :b :d]`; `(conj [:a :b :c] :d)` appends `:d`. `peek` reads the last element, and `pop` removes it. For a portion away from the tail, use `subvec` rather than treating deletion as a vector strength. section 12.1 section 12.2

An index is not a value

`(contains? [1 2 :a :b] 3)` is `true`: position 3 exists. `(contains? [1 2 :a :b] :a)` is `false`, even though `:a` is an element. To test for a value instead, the underlying Java `.contains` method is one option. section 12.1

Vectors work with sequence operations, but are not themselves sequence types: `seq?` returns false. Sequence operations implicitly turn them into sequences. Choose `mapv` or `filterv` when the result should be a vector, and keep that collection choice consistent when designing functions. section 12.1 section 12.11

`vec` builds a persistent vector from a collection, iterable, Java array, or `nil`. It preserves order when the input has an order; sets and unsorted maps provide no specific resulting order. It cannot convert transients or structs. Take care with Java arrays of reference types containing 32 elements or fewer: the resulting vector can alias the array, so later array mutation can change its apparent value. section 12.5

How Clojure: The Essential Reference covers it

How deep it goes
Explains operations, sequence behavior, and vec's input contract and array caveat, without detailing vector implementation internals.
Examples
Shows indexed access and updates, positional contains? results, and vec conversion with a Java-array aliasing example.
What it assumes
Introduces vector literals and zero-based indexing while using basic Clojure collection functions in examples.
What you can do after
Apply it via Clojure's indexed operations and vec while distinguishing vectors from sequences and guarding against array aliasing.
How it connects
Connects vectors to sequences, mapv, filterv, subvec, persistent collections, and Java arrays.

Also explained in

Compare how 11 books explain vector →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.