Lisp - Accessing Elements of Vector



A Vector is single dimensional array in LISP. In LISP, we've multiple ways to access elements of a vector based on its type like simple vector, adjustable vector etc. In this chapter, we'll discuss various methods of LISP using which we can access vector's elements.

Simple Vector - Use of svref function

A simple vector is a single dimensional fix sized array with no fill pointer and svref is the most commonly used and efficient function to access an element by its index as shown below−

main.lisp

; create a vector
(setf my-vector (vector  11 12 13 14))  

; access and print first element using index as 0; 11
(print(svref my-vector 0))
(terpri)
; access and print third element using index as 2; 13
(print(svref my-vector 2))

Output

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

11 
13

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.

Use of Generic aref function

aref is a generic function to access elements of arrays and works with both single as well as multidimensional arrays. We can use aref in case of arrays with fill-pointers as well.

main.lisp

; create a vector
(setf my-vector (make-array 4 :initial-contents '(11 12 13 14)))  

; access and print first element using index as 0; 11
(print(aref my-vector 0))
(terpri)
; access and print third element using index as 2; 13
(print(aref my-vector 2))

Output

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

11 
13

Use of Generic elt function

elt function is used to access elements of a sequence which can be a list, vector or string. Following example showcases how to use elt function to access elements of a vector

main.lisp

; create a vector
(setf my-vector (vector  11 12 13 14))  

; access and print first element using index as 0; 11
(print(elt my-vector 0))
(terpri)
; access and print third element using index as 2; 13
(print(elt my-vector 2))

Output

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

11 
13

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