1 Welcome to PLT Scheme
2 Scheme Essentials
3 Built-In Datatypes
4 Expressions and Definitions
5 Programmer-Defined Datatypes
6 Modules
7 Input and Output
8 Contracts
9 Classes and Objects
10 Exceptions and Control
11 Iterations and Comprehensions
12 Regular-Expression Matching (Regexps)
13 Pattern Matching
14 Quasiquoting
15 Units (Higher-Order Modules)
16 Threads
17 Syntactic Extension (Macros)
18 Reflection and Dynamic Evaluation
19 Reader Extension
20 Security
21 Memory Management
22 Performance
23 Foreign-Function Interface (FFI)
24 Scripts
25 Graphical User Interfaces (GUIs)
26 More Tools
Index

contents

 index

← prev  up  next →

 

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:

  > (list->vector (map string-titlecase

                       (vector->list #3("three" "blind" "mice"))))

  #3("Three" "Blind" "Mice")

Vectors in PLT Scheme Reference provides more on vectors and vector procedures.

 

contents

 index

← prev  up  next →