svref
svref Accessor
Syntax:
svref simple-vector index → element
(setf (svref simple-vector index**)** new-element**)**
Arguments and Values:
simple-vector—a simple vector .
index—a valid array index for the simple-vector.
element, new-element—an object (whose type is a subtype of the array element type of the simple-vector).
Description:
Accesses the element of simple-vector specified by index.
Examples:
(simple-vector-p (setq v (vector 1 2 ’sirens))) → true
(svref v 0) → 1
(svref v 2) → SIRENS
(setf (svref v 1) ’newcomer) → NEWCOMER
v → #(1 NEWCOMER SIRENS)
See Also:
aref, sbit, schar, vector, Section 3.2.1 (Compiler Terminology)
Notes:
svref is identical to aref except that it requires its first argument to be a simple vector . (svref v i) ≡ (aref (the simple-vector v) i)
Expanded Reference: svref
Basic Element Access
svref accesses elements of a simple vector by index. It is identical to aref but requires its first argument to be a simple vector, which may allow optimized access.
(let ((v (vector 'a 'b 'c 'd)))
(list (svref v 0) (svref v 2)))
=> (A C)
Setting Elements with SETF
svref works with setf to modify elements in place.
(let ((v (vector 1 2 3 4 5)))
(setf (svref v 2) 99)
v)
=> #(1 2 99 4 5)
Only Works on Simple Vectors
svref requires a simple vector -- a one-dimensional array with element-type t, no fill pointer, not adjustable, and not displaced. Strings, bit vectors, and vectors with fill pointers are not valid arguments.
;; This works: vector creates a simple vector
(svref (vector 'x 'y 'z) 1)
=> Y
;; simple-vector-p can verify the argument type
(let ((v (make-array 3 :initial-element 0)))
(list (simple-vector-p v)
(svref v 0)))
=> (T 0)
Performance Consideration
When you know your array is a simple vector, using svref communicates this to both the reader and the compiler, potentially enabling faster element access.
(let ((v (vector 10 20 30 40 50)))
;; svref and aref return the same value
(= (svref v 3) (aref v 3)))
=> T