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 80 81 82 83 84 85 86 87 88 89 90
|
<HTML>
<HEAD>
<TITLE>Common LISP Hints: Iteration</TITLE>
</HEAD>
<BODY>
<A HREF="LISP-tutorial-17.html"><IMG SRC="prev.gif" ALT="Previous"></A>
<A HREF="LISP-tutorial-19.html"><IMG SRC="next.gif" ALT="Next"></A>
<A HREF="LISP-tutorial.html#toc18"><IMG SRC="toc.gif" ALT="Contents"></A>
<HR>
<H2><A NAME="s18">18. Iteration</A></H2>
<P>The simplest iteration construct in LISP is <CODE>loop</CODE>: a <CODE>loop</CODE> construct
repeatedly executes its body until it hits a <CODE>return</CODE> special form. For
example,</P>
<P>
<BLOCKQUOTE><CODE>
<PRE>
> (setq a 4)
4
> (loop
(setq a (+ a 1))
(when (> a 7) (return a)))
8
> (loop
(setq a (- a 1))
(when (< a 3) (return)))
NIL
</PRE>
</CODE></BLOCKQUOTE>
</P>
<P>The next simplest is <CODE>dolist</CODE>: <CODE>dolist</CODE> binds a variable to the
elements of
a list in order and stops when it hits the end of the list.</P>
<P>
<BLOCKQUOTE><CODE>
<PRE>
> (dolist (x '(a b c)) (print x))
A
B
C
NIL
</PRE>
</CODE></BLOCKQUOTE>
</P>
<P><CODE>Dolist</CODE> always returns <CODE>nil</CODE>. Note that the value of <CODE>x</CODE> in the above
example was never <CODE>nil</CODE>: the<CODE> NIL</CODE> below the C was the value
that <CODE>dolist</CODE>
returned, printed by the read-eval-print loop.</P>
<P>The most complicated iteration primitive is called <CODE>do</CODE>. A <CODE>do</CODE> statement
looks like this: </P>
<P>
<BLOCKQUOTE><CODE>
<PRE>
> (do ((x 1 (+ x 1))
(y 1 (* y 2)))
((> x 5) y)
(print y)
(print 'working)
)
1
WORKING
2
WORKING
4
WORKING
8
WORKING
16
WORKING
32
</PRE>
</CODE></BLOCKQUOTE>
</P>
<P>The first part of a <CODE>do</CODE> specifies what variables to bind, what their
initial values are, and how to update them. The second part specifies a
termination condition and a return value. The last part is the body. A
do form binds its variables to their initial values like a <CODE>let</CODE>, then
checks the termination condition. As long as the condition is false, it
executes the body repeatedly; when the condition becomes true, it
returns the value of the return-value form.</P>
<P>The <CODE>do</CODE>* form is to <CODE>do</CODE> as <CODE>let</CODE>* is to <CODE>let</CODE>.</P>
<HR>
<A HREF="LISP-tutorial-17.html"><IMG SRC="prev.gif" ALT="Previous"></A>
<A HREF="LISP-tutorial-19.html"><IMG SRC="next.gif" ALT="Next"></A>
<A HREF="LISP-tutorial.html#toc18"><IMG SRC="toc.gif" ALT="Contents"></A>
</BODY>
</HTML>
|