Lisp - Accessing Element of Sequence



A sequence is an abstract data type in lisp. Vectors, Lists, Strings are commonly sequences. Lisp provides various options to access each element of a sequence. In this chapter, we've going to discuss each of them in details with examples.

Access Elements of a List

A list element can be accessed via car, cdr and nth functions.

Using car

car function returns the first element of the list.

; print A
(write(car '(a b c)))

Output

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

A

Using cdr

cdr function returns rest of the elements after removing first element of the list.

; print B C
(write(cdr '(a b c)))

Output

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

(B C)

Using nth

nth function returns element at particular index. Index starts from 0.

; print C
(write(nth 2 '(a b c)))

Output

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

C

Access Elements of a Vector and String

A single dimensional array is termed as vector and string can be treated as a sequence of characters. We can use elt and aref functions to get an element of vector or a character at particular index where indexes start from zero.

Using elt

elt function returns element at particular index. Index starts from 0.

; print C
(write(elt #(a b c) 2))
(terpri)
; print #\o
(write(elt "tutorialpoint" 3))

Output

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

C
#\o

Using aref

aref function returns element at particular index. Index starts from 0.

; print C
(write(aref #(a b c) 2))
(terpri)
; print #\o
(write(aref "tutorialpoint" 3))

Output

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

C
#\o

Important Points to Consider

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

  • List vs Vector access − List in LISP are linked list, so accessing list element is slower than vector or string in case of large size of list.

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

Advertisements