Reading — step 1 of 5
Learn
~1 min readHash Tables, Vectors, Strings
Lists are linked. Vectors are arrays — O(1) indexed access.
Creating
#(1 2 3 4 5) ; literal vector
(vector 1 2 3 4 5) ; constructor
(make-array 5) ; size 5, all nil
(make-array 5 :initial-element 0) ; size 5, all 0
(make-array '(3 3) :initial-element 0) ; 3x3 matrix
Access
(defparameter *v* #(10 20 30 40))
(aref *v* 0) ; 10 — 0-indexed
(aref *v* 2) ; 30
(setf (aref *v* 1) 99) ; mutate
(length *v*) ; 4
aref is the universal array accessor. Works for vectors, multi-dim arrays, strings (which are character vectors).
Adjustable vectors
(defparameter *v* (make-array 0
:element-type t
:adjustable t
:fill-pointer 0))
(vector-push-extend 'a *v*)
(vector-push-extend 'b *v*)
(vector-push-extend 'c *v*)
*v* ; #(a b c)
vector-push-extend grows the underlying storage as needed — like a dynamic array.
Iteration
(loop for x across *v* do (print x))
(map 'vector (lambda (x) (* x 2)) *v*)
(reduce #'+ *v*)
Multi-dimensional arrays
(defparameter *grid* (make-array '(3 3) :initial-element 0))
(setf (aref *grid* 1 1) 5)
(aref *grid* 1 1) ; 5
Specialized arrays
Declare element type for performance:
(make-array 1000 :element-type '(unsigned-byte 8)) ; byte array
(make-array 1000 :element-type 'single-float)
(make-array 1000 :element-type 'fixnum)
The compiler can pack these tightly and unbox elements — much faster than generic arrays of T.
Lists vs vectors
- Lists: O(n) random access, O(1) cons, easy recursion, the natural Lisp data
- Vectors: O(1) random access, O(n) insert in middle, better for hot loops
Lists for AST manipulation, recursion, code-as-data. Vectors for tight numerics, image data, anything index-heavy.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…