lispclisp

Lisp: How to set element in list of lists?


I am familiar with how to set elements in a 2D array, which can be done using the following statement.

(setf (aref array2D 0 0) 3)

However, I am not familiar how to set elements in a list of lists, such as the following input: '((1) (2) (2) (1)). I can't use aref, since it only works on arrays.


Solution

  • As mentioned, while aref works on arrays, elt works on sequences which can be:

    1. an ordered collection of elements
    2. a vector or a list.
    * (setf test-list '((1) (2) (2) (1)))
    ((1) (2) (2) (1))
    * (setf (elt test-list 2) 'hi)
    HI
    * test-list
    ((1) (2) HI (1))
    

    You can indeed use variables in place of fixed offsets:

    * (setf test-list '((1) (2) (2) (1)))
    ((1) (2) (2) (1))
    * (setf offset 2)
    2
    * (setf (elt test-list offset) 'hi)
    HI
    * test-list
    ((1) (2) HI (1))