3.9 Vectors
A vector is a fixed-length array of arbitarary values. Unlike a list, a vector supports constant-time access and update of its elements.
A vector prints similar to a list – as a parenthesized sequence of its elements – but a vector is prefixed with # and the length of the vector. The vector length is optional for a vector as an expression. Also, a vector as an expression implicitly quotes the forms for its content, which means that identifiers and parenthesized forms in a vector constant represent symbols and lists.
Reading Vectors in PLT Scheme Reference documents the fine points of the syntax of vectors.
Examples: |
> #("a" "b" "c") |
#3("a" "b" "c") |
> #(name (that tune)) |
#2(name (that tune)) |
> (vector-ref #3("a" "b" "c") 1) |
"b" |
> (vector-ref #2(name (that tune)) 1) |
(that tune) |
When the last n vector elements of a vector are the same value (as determined by eq?), then the last n-1 instances are omitted from the printed form. The vector length shown after the leading # effectively indicates when repeated trailing elements are omitted. The same conventions apply for vectors as expressions.
Examples: |
> (define v (make-vector 100 ".")) |
> v |
#100(".") |
> (vector-set! v 1 "!") |
> v |
#100("." "!" ".") |
> (vector-ref #10("." "?") 8) |
"?" |
Like strings, a vector is either mutable or immutable, and vectors written directly as expressions are immutable.
Vector can be converted to lists and vice-versa via list->vector and vector->list; such conversions are particularly useful in combination with predefined procedures on lists. When allocating extra lists seems too expensive, use consider using looping forms like fold-for, which recognize vectors as well as lists.
Examples: | ||
| ||
#3("Three" "Blind" "Mice") |
Vectors in PLT Scheme Reference provides more on vectors and vector procedures.