emacs.d/clones/lisp/colinallen.dnsalias.org/lp/node36.html

51 lines
2.3 KiB
HTML
Raw Normal View History

2022-08-02 12:34:59 +02:00
<!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> Iteration Using Dolist</TITLE>
</HEAD>
<BODY>
<meta name="description" value=" Iteration Using Dolist">
<meta name="keywords" value="lp">
<meta name="resource-type" value="document">
<meta name="distribution" value="global">
<P>
<BR> <HR>
<A HREF="node37.html"><IMG ALIGN=BOTTOM ALT="next" SRC="next_motif.gif"></A>
<A HREF="node29.html"><IMG ALIGN=BOTTOM ALT="up" SRC="up_motif.gif"></A>
<A HREF="node35.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="node37.html"> When To Use </A>
<B>Up:</B>
<A HREF="node29.html"> Recursion and Iteration</A>
<B> Previous:</B>
<A HREF="node35.html"> Local Variables Using </A>
<BR> <HR> <P>
<H1> Iteration Using Dolist</H1>
<P>
Dolist is very much like dotimes, except that the iteration is controlled by the length of a list, rather than by the value of a count. Here is the general form for dolist:
<BLOCKQUOTE>
<PRE> (dolist (&lt;next-element&gt; &lt;target-list&gt; &lt;result&gt; ) &lt;body&gt; )
</PRE>
</BLOCKQUOTE>
In a dolist statment result and body work just as in dotimes. Next-element is the name of a variable which is intially set to the first element of target-list (which must therefore be a list). The next time through, next-element is set to the second element of target-list and so on until the end of target-list is reached, at which point result-form is evaluated and returned.
<P>
Here is num-sublists done as an example:
<BLOCKQUOTE>
<PRE> (defun num-sublists-i (lis)
(let ((result 0))
(dolist (next lis result)
(if (listp next)
(setf result (1+ result))))))
</PRE>
</BLOCKQUOTE>
The function num-sublists-i works because result is incremented only whenever the current element of the list indicated by next is itself a list. Notice that in the case where the next element of the list is not itself a list there is no need to do anything. Thus, in the if statement of the definition it is possible to omit the else clause entirely.
<P>
<BR> <HR>
<P>
<ADDRESS>
<I>&#169; Colin Allen &amp; Maneesh Dhagat <BR>
March 2007 </I>
</ADDRESS>
</BODY>