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

84 lines
2.4 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> Selectors: First and Rest</TITLE>
</HEAD>
<BODY>
<meta name="description" value=" Selectors: First and Rest">
<meta name="keywords" value="lp">
<meta name="resource-type" value="document">
<meta name="distribution" value="global">
<P>
<BR> <HR>
<A HREF="node11.html"><IMG ALIGN=BOTTOM ALT="next" SRC="next_motif.gif"></A>
<A HREF="node7.html"><IMG ALIGN=BOTTOM ALT="up" SRC="up_motif.gif"></A>
<A HREF="node9.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="node11.html"> Changing Variable Values</A>
<B>Up:</B>
<A HREF="node7.html"> Some Primitive Functions</A>
<B> Previous:</B>
<A HREF="node9.html"> Quote</A>
<BR> <HR> <P>
<H2> Selectors: First and Rest</H2>
<P>
There are two primitive list selectors. Historically, these were
known as car and cdr, but these names were hard to explain since they
referred to the contents of various hardware registers in computers
running Lisp. In Common Lisp the functions have been given
alternative names, first and rest, respectively. (You can still use
the old names in Common Lisp. One of us learned Lisp in the old days, so
occasionally we'll use car or cdr instead of first or rest.)
<P>
First takes a list as an argument and returns the first element of
that list. It works like this:
<P>
<BLOCKQUOTE>
<PRE>&gt; (first '(a s d f))
a
&gt; (first '((a s) d f))
(a s)
</PRE>
</BLOCKQUOTE>
Rest takes a list as an argument and returns the list, minus its
first element.
<P>
<BLOCKQUOTE>
<PRE>&gt; (rest '(a s d f))
(s d f)
&gt; (rest '((a s) d f))
(d f)
&gt; (rest '((a s) (d f)))
((d f))
</PRE>
</BLOCKQUOTE>
You can use setq to save yourself some typing. Do the following:
<P>
<BLOCKQUOTE>
<PRE>&gt; (setq a '(a s d f))
(a s d f)
</PRE>
</BLOCKQUOTE>
You can now use a instead of repeating the list (a s d f) every time.
So:
<P>
<BLOCKQUOTE>
<PRE>&gt; (first a)
a
&gt; (rest a)
(s d f)
&gt; (first (rest a))
s
</PRE>
</BLOCKQUOTE>
You can figure out the rest, like how to get at the third and fourth
elements of the list using first and rest.
<P>
<BR> <HR>
<P>
<ADDRESS>
<I>&#169; Colin Allen &amp; Maneesh Dhagat <BR>
March 2007 </I>
</ADDRESS>
</BODY>