Lisp - Modifications to Vectors



A Vector is single dimensional array and we can modify a vector in LISP using setf operation with svref for simple vectors and aref for generic vectors. Let's discuss each of the option one by one.

Using setf with svef for Simple Vectors

main.lisp

; create a vector; #(A B C D)
(setf my-vector (vector 'a 'b 'c 'd))

; print the vector
(print my-vector)

; update second element to z
(setf (svref my-vector 1) 'z)
(terpri)
; print the updated vector; #(A Z C D)
(print my-vector)  

Output

When you execute the code, it returns the following result −

#(A B C D) 
#(A Z C D) 

Important Points to Consider

  • Zero based Index − First element is at index 0 as indexes start from 0 in LISP.

  • Error Handling − If an invalid index is used, then error will be thrown.

Using setf with aref for Generic Vectors

main.lisp

; create a vector; #(10 20 30 40)
(setf my-vector (make-array 4 :initial-contents '(10 20 30 40)))

; print the vector
(print my-vector)

; update second element to 50
(setf (aref my-vector 1) 50)
(terpri)
; print the updated vector; #(10 50 30 40)
(print my-vector)  

Output

When you execute the code, it returns the following result −

#(10 20 30 40) 
#(10 50 30 40) 

Important Points to Consider

  • Zero based Index − First element is at index 0 as indexes start from 0 in LISP.

  • svref − svref function is specific to access elements of simple vectors. In case of multidimensional or adjustable vectors, aref is preferred choice to access elements.

  • Error Handling − If an invalid index is used, then error will be thrown.

Advertisements