Vectors

Vectors

Robbert Haarman

2010-12-11


Introduction

A vector is much like a list, with one important difference: a list consists of pairs that contain the elements, but a vector consists only of the elements themselves in conecutive memory locations. Vectors occupy less space and their elements can be accessed quicker than in lists. On the other hand, vectors are less flexible than lists.


Operations on Vectors


; Create a vector
(vector 1 2 3) ; => #(1 2 3)
'#(1 2 3) ; => #(1 2 3)

; Create a vector of specified length
(make-vector 3) ; returns a vector of lenght 3
(make-vector 3 0) ; => #(0 0 0)

; Test if something is a vector
(vector? '#(1 2 3)) ; => #t
(vector? '(1 2 3)) ; => #f

; Lenght of a vector
(vector-lenght '#(1 2 3)) ; => 3

; Get element
(vector-ref '#(1 2 3) 2) ; => 3

; Set element
(define a (vector 1 2 3))
(vector-set! a 1 'foo) ; a is now #(foo 2 3)

; Set all elements
(define a (vector 1 2 3))
(vector-fill! a 0) ; a is now #(0 0 0)

; Convert between vectors and lists
(vector->list '#(1 2 3)) ; => (1 2 3)
(list->vector '(1 2 3)) ; => #(1 2 3)
Valid XHTML 1.1! Valid CSS! Viewable with Any Browser