Search code examples
arrayscommon-lisp

How to use dynamic variables as elements of an array


I would like to use an array or list to store dynamic variables for later retrieval via an index. So if I have:

(defparameter *foo* '(1 2 3))
(defparameter *bar* '(3 4 5))
(defparameter *baz*
  (make-array 2 :initial-contents '(*foo* *bar*)))

I would like to retrieve *foo* by calling (aref *baz* 0) and have this return '(1 2 3)

Of course, this doesn't work and the *foo* stored in *baz* isn't even the special variable I defined at top-level, as shown when I try to do (elt (aref *baz* 0) 1) which only returns an error and not the value 2. Let me say I am new to Common Lisp and I don't even know how to describe this question in a way that helped me in searching through CLHS, etc. Any help would be appreciated!


Solution

  • You need to understand the difference between a symbol (which is a data type in Lisp) and its value. The symbol exists as an object. The value of a symbol is either the result of an evaluation or can be retrieved by accessing the symbol value. Lisp is one of the few languages where a symbol is a first class datatype and which has also a value which can be set and bound.

    > '*foo*
    *foo*       ; the symbol *foo* itself
    
    > *foo*
    (1 2 3)     ; the value of the symbol *foo* -> this list
    
    > (eval '*foo*)
    (1 2 3)     ; the value of the symbol *foo* -> this list
    
    
    > (symbol-value '*foo*)
    (1 2 3)     ; the value of the symbol *foo* -> this list
    

    One can retrieve the value of a symbol with the function symbol-value:

    (symbol-value '*foo*)
    
    (let ((symbol '*foo*))
      (symbol-value symbol))