Lisp - Accessing Element of a List
In LISP, List is implmented as single linked list. LISP provides several methods to access element of a list. In this chapter, we're uncovering commonly used methods with examples.
car and cdr, Fundamental Accessors
A list element can be accessed via car, cdr functions.
car− can be treated as "Content of Address Register". car method returns the first element of the list.
cdr− can be treated as "Content of Decrement Register". car method returns the rest of the list without first element.
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)
cadr and caddr etc., Composite Accessors
cadr, caddr are shorthand for nested car and cdr calls. cadr is equivalent to (car(cdr ...)),caddr is equivalent to (car(cdr (cdr...))) and so.
a is used to represent car and d is used to represent cdr in nested calls. We can chain upto four a or d between c and r. For higher value access, we can use nth or recursive calls.
Using cadr, caddr
Following code shows the usage of cadr and caddr functions.
; print B (write(cadr '(a b c))) (terpri) ; print C (write(caddr '(a b c)))
Output
When you execute the code, it returns the following result −
B C
Using nth and elt, Positional Accessors
nth function returns element at particular index. Index starts from 0. Whereas elt also returns element at particular index starting from 0 but it can work with vectors.
; print C (write(nth 2 '(a b c))) (terpri) ; print C (write(elt '(a b c) 2))
Output
When you execute the code, it returns the following result −
C
Using Recursion
Following code shows the recursive way to print all elements of a list.
(defun print-list (lst)
; if list is not empty
(when lst
; print first element
(print (car lst))
; print sub-list recursively
(print-list (cdr lst))))
(print-list '(a b c d e))
Output
When you execute the code, it returns the following result −
A B C D E