1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
|
<HTML>
<HEAD>
<TITLE>Common LISP Hints: Lists</TITLE>
</HEAD>
<BODY>
<A HREF="LISP-tutorial-5.html"><IMG SRC="prev.gif" ALT="Previous"></A>
<A HREF="LISP-tutorial-7.html"><IMG SRC="next.gif" ALT="Next"></A>
<A HREF="LISP-tutorial.html#toc6"><IMG SRC="toc.gif" ALT="Contents"></A>
<HR>
<H2><A NAME="s6">6. Lists</A></H2>
<P>You can build many structures out of conses. Perhaps the simplest is a
linked list: the car of each cons points to one of the elements of the
list, and the cdr points either to another cons or to <CODE>nil</CODE>. You can
create such a linked list with the list fuction:</P>
<P>
<BLOCKQUOTE><CODE>
<PRE>
> (list 4 5 6)
(4 5 6)
</PRE>
</CODE></BLOCKQUOTE>
</P>
<P>Notice that LISP prints linked lists a special way: it omits some of
the periods and parentheses. The rule is: if the <CODE>cdr</CODE> of a cons is
<CODE>nil</CODE>,
LISP doesn't bother to print the period or the <CODE>nil</CODE>; and if the
<CODE>cdr</CODE> of
cons A is cons B, then LISP doesn't bother to print the period for cons
A or the parentheses for cons B. So:</P>
<P>
<BLOCKQUOTE><CODE>
<PRE>
> (cons 4 nil)
(4)
> (cons 4 (cons 5 6))
(4 5 . 6)
> (cons 4 (cons 5 (cons 6 nil)))
(4 5 6)
</PRE>
</CODE></BLOCKQUOTE>
</P>
<P>The last example is exactly equivalent to the call <CODE>(list 4 5 6)</CODE>. Note
that <CODE>nil</CODE> now means the list with no elements: the cdr of (a b), a list
with 2 elements, is (b), a list with 1 element; and the cdr of (b), a
list with 1 element, is <CODE>nil</CODE>, which therefore must be a list with no
elements.</P>
<P>The car and cdr of <CODE>nil</CODE> are defined to be nil.</P>
<P>If you store your list in a variable, you can make it act like a stack:</P>
<P>
<BLOCKQUOTE><CODE>
<PRE>
> (setq a nil)
NIL
> (push 4 a)
(4)
> (push 5 a)
(5 4)
> (pop a)
5
> a
(4)
> (pop a)
4
> (pop a)
NIL
> a
NIL
</PRE>
</CODE></BLOCKQUOTE>
</P>
<HR>
<A HREF="LISP-tutorial-5.html"><IMG SRC="prev.gif" ALT="Previous"></A>
<A HREF="LISP-tutorial-7.html"><IMG SRC="next.gif" ALT="Next"></A>
<A HREF="LISP-tutorial.html#toc6"><IMG SRC="toc.gif" ALT="Contents"></A>
</BODY>
</HTML>
|