Arrays & Vectors

  • Accessing an element by its index is fast: O(1)
  • Contiguous data in memory, unlike lists (just regular computer science stuff)
(defparameter *vector* (vector 0 1 2 3))

;; access:
(aref *vector* 3)

;; or the function elt, but it's generic, for sequences (thus a bit slower).

;; set:
(setf (aref *vector* 3) 30)

;; can't set beyond its boundaries:
(setf (aref *vector* 100) 100)

;; but a "vector" is only a simple vector:
;; it's fixed, we can't augment it.

(vector-push 9 *vector*)
;; not of type (AND VECTOR (NOT SIMPLE-ARRAY))
;; because it is a simple vector.
(type-of *vector*)

;; look at its documentation
(documentation 'vector 'function)

Vectors we can extend: adjustable arrays.

;; They must be: adjustable, and have a fill-pointer.
(defparameter v (make-array 1 :fill-pointer t
                              :adjustable t
                              :initial-element :a))

(fill-pointer v)

;; vector-push-extend:
;; - add element at the end
;; - move the fill-pointer (the fill-pointer defines the end of the array)
(vector-push-extend :b v)

;; vector-pop
(vector-pop v)

;; vector-push, similar to vector-push-extend except it won't extend automatically the array.

Coerce: transform a vector into a list.

(coerce *vector* 'list)

(loop for elt :across *vector*
      do (print elt))

(map 'vector #'1+ *vector*)