next up previous
Contents Next: Property Lists Up: Simple Data Structures Previous: Simple Data Structures

Association Lists

An association list is any list of the following form:

((<key1>  ...<expressions> )
 (<key2>  ...<expressions> )....)
The keys should be atoms. Following each key, you can put any sequence of Lisp expressions.

Use the interpreter to enter this example of an association list:

> (setf person1 '((first-name john)
                 (last-name smith)
                 (age 23)
                 (children jane jim)))
((FIRST-NAME JOHN) (LAST-NAME SMITH) (AGE 23) 
 (CHILDREN JANE JIM))
Lisp provides a function, assoc, to retrieve information easily from association lists given a retrieval key.

For example:

> (assoc 'age person1)
(AGE 23)

> (assoc 'children person1)
(CHILDREN JANE JIM)
Notice that assoc returns the entire key-expression sublist. It does not matter to assoc what order the keys appear in the association list or how many expressions are associated with each key.

Setf can be used to change particular values. For example, here is a function that can be used on a birthday to update a person's age automatically.

(defun make-older (person)
  (setf (second (assoc 'age person))
        (1+ (second (assoc 'age person)))))
Have your Lisp interpreter evaluate this definition, then see that it works:

> (make-older person1)
24

> (assoc 'age person1)
(AGE 24)
Assoc will return nil if the key is not found.

> (assoc 'sex person1)
NIL
But it is very easy to add new key-expression sublists, again using setf.

> (setf person1 (cons '(sex male) person1))
((SEX MALE) (FIRST-NAME JOHN) (LAST-NAME SMITH) (AGE 24) 
 (CHILDREN JANE JIM))



© Colin Allen & Maneesh Dhagat
March 2007