emacs.d/clones/colinallen.dnsalias.org/lp/node51.html

99 lines
2.9 KiB
HTML

<!DOCTYPE HTML PUBLIC "-//W3O//DTD W3 HTML 2.0//EN">
<!Originally converted to HTML using LaTeX2HTML 95 (Thu Jan 19 1995) by Nikos Drakos (nikos@cbl.leeds.ac.uk), CBLU, University of Leeds >
<HEAD>
<TITLE> Association Lists</TITLE>
</HEAD>
<BODY>
<meta name="description" value=" Association Lists">
<meta name="keywords" value="lp">
<meta name="resource-type" value="document">
<meta name="distribution" value="global">
<P>
<BR> <HR>
<A HREF="node52.html"><IMG ALIGN=BOTTOM ALT="next" SRC="next_motif.gif"></A>
<A HREF="node50.html"><IMG ALIGN=BOTTOM ALT="up" SRC="up_motif.gif"></A>
<A HREF="node50.html"><IMG ALIGN=BOTTOM ALT="previous" SRC="previous_motif.gif"></A> <BR>
<A HREF="lp.html"><B>Contents</B></A>
<B> Next:</B>
<A HREF="node52.html"> Property Lists</A>
<B>Up:</B>
<A HREF="node50.html"> Simple Data Structures </A>
<B> Previous:</B>
<A HREF="node50.html"> Simple Data Structures </A>
<BR> <HR> <P>
<H1> Association Lists</H1>
<P>
An association list is any list of the following form:
<BLOCKQUOTE>
<PRE>((&lt;key1&gt; ...&lt;expressions&gt; )
(&lt;key2&gt; ...&lt;expressions&gt; )....)
</PRE>
</BLOCKQUOTE>
The keys should be atoms. Following each key, you can put any sequence of Lisp expressions.
<P>
Use the interpreter to enter this example of an association list:
<P>
<BLOCKQUOTE>
<PRE>&gt; (setf person1 '((first-name john)
(last-name smith)
(age 23)
(children jane jim)))
((FIRST-NAME JOHN) (LAST-NAME SMITH) (AGE 23)
(CHILDREN JANE JIM))
</PRE>
</BLOCKQUOTE>
Lisp provides a function, assoc, to retrieve information easily from association lists given a retrieval key.
<P>
For example:
<P>
<BLOCKQUOTE>
<PRE>&gt; (assoc 'age person1)
(AGE 23)
&gt; (assoc 'children person1)
(CHILDREN JANE JIM)
</PRE>
</BLOCKQUOTE>
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.
<P>
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.
<P>
<BLOCKQUOTE>
<PRE>(defun make-older (person)
(setf (second (assoc 'age person))
(1+ (second (assoc 'age person)))))
</PRE>
</BLOCKQUOTE>
Have your Lisp interpreter evaluate this definition, then see that it works:
<P>
<BLOCKQUOTE>
<PRE>&gt; (make-older person1)
24
&gt; (assoc 'age person1)
(AGE 24)
</PRE>
</BLOCKQUOTE>
Assoc will return nil if the key is not found.
<P>
<BLOCKQUOTE>
<PRE>&gt; (assoc 'sex person1)
NIL
</PRE>
</BLOCKQUOTE>
But it is very easy to add new key-expression sublists, again using setf.
<P>
<BLOCKQUOTE>
<PRE>&gt; (setf person1 (cons '(sex male) person1))
((SEX MALE) (FIRST-NAME JOHN) (LAST-NAME SMITH) (AGE 24)
(CHILDREN JANE JIM))
</PRE>
</BLOCKQUOTE>
<P>
<BR> <HR>
<P>
<ADDRESS>
<I>&#169; Colin Allen &amp; Maneesh Dhagat <BR>
March 2007 </I>
</ADDRESS>
</BODY>