Next: , Previous: Vector Syntax, Up: Vectors


22.3.2 Dynamic Vector Creation and Validation

Instead of creating a vector implicitly by using the read syntax just described, you can create a vector dynamically by calling one of the vector and list->vector primitives with the list of Scheme values that you want to place into a vector. The size of the vector thus created is determined implicitly by the number of arguments given.

— Scheme Procedure: vector [args ...]
— Scheme Procedure: list->vector [args ...]
— C Function: scm_vector (args)

Return a newly allocated vector whose elements contain the given args. Analogous to ‘list’. (r5rs)

          (vector 'a 'b 'c)
          ⇒ #(a b c)

(As an aside, an interesting implementation detail is that the Guile reader reads the #(...) syntax by reading everything but the initial # as a list, and then passing the list that results to list->vector. Notice how neatly this fits with the similarity between the read (and print) syntaxes for lists and vectors.)

The inverse operation is vector->list:

— Scheme Procedure: vector->list vector
— C Function: scm_vector_to_list (vector)

Return a newly allocated list of the objects contained in the elements of vector. (r5rs)

          (vector->list '#(dah dah didah))
          ⇒ (dah dah didah)
          (list->vector '(dididit dah))
          ⇒ #(dididit dah)

To allocate a vector with an explicitly specified size (currently limited to 2^24), use make-vector. With this primitive you can also specify an initial value for the vector elements (the same value for all elements, that is).

— Scheme Procedure: make-vector k [fill]
— C Function: scm_make_vector (k, fill) |1 |1 |0

Return a newly allocated vector of k elements. If a second argument is given, then each element is initialized to fill. Otherwise the initial contents of each element is unspecified. (r5rs)

To check whether an arbitrary Scheme value is a vector, use the vector? primitive:

— Scheme Procedure: vector? obj
— C Function: scm_vector_p (obj)

Return #t if obj is a vector, otherwise returns #f. (r5rs)