Debian Codegraph @

doc/iterate.texinfo

raw
1 \input texinfo @c -*- Mode: Texinfo; Mode: auto-fill -*-
2 @c %**start of header
3 @setfilename iterate.info
4 @settitle The Iterate Manual and Paper
5 @exampleindent 2
6
7 @c @documentencoding utf-8
8
9 @macro iter {}
10 @code{iterate}
11 @end macro
12
13 @macro mathx {tex, non-tex}
14 @iftex
15 @math{\tex\}
16 @end iftex
17 @ifnottex
18 @emph{\non-tex\}
19 @end ifnottex
20 @end macro
21
22 @macro impnote {text}
23 @quotation Implementor's note
24 @emph{\text\}
25 @end quotation
26 @end macro
27
28 @c Set ROMANCOMMENTS to get comments in roman font.
29 @ifset ROMANCOMMENTS
30 @alias lispcmt = r
31 @end ifset
32 @ifclear ROMANCOMMENTS
33 @alias lispcmt = asis
34 @end ifclear
35
36 @c Index for iterate clauses.
37 @defindex it
38
39 @macro clauseu {name1}
40 @itindex \name1\
41 @c
42 @end macro
43
44 @macro claused {name1, name2}
45 @itindex \name1\@dots{}\name2\
46 @c
47 @end macro
48
49 @macro clauset {name1, name2, name3}
50 @itindex \name1\@dots{}\name2\@dots{}\name3\
51 @c
52 @end macro
53
54 @macro k {what}
55 @code{\what\}
56 @end macro
57
58 @iftex
59 @alias v = asis
60 @alias cl = code
61 @end iftex
62
63 @ifnottex
64 @alias v = var
65 @alias cl = strong
66 @end ifnottex
67
68 @c Show variables, clauses, and concepts in the same index.
69 @syncodeindex it cp
70 @syncodeindex vr cp
71
72 @copying
73 Copyright @copyright{} 1989 Jonathan Amsterdam <jba at ai.mit.edu> @*
74 @c Copyright @copyright{} 2006 Lu@'{@dotless{i}}s Oliveira
75 @c <loliveira at common-lisp.net> @*
76
77 @quotation
78 The present manual is a conversion of Jonathan Amsterdam's ``The
79 Iterate Manual'', @acronym{MIT} @acronym{AI} Memo No.@: 1236. Said memo
80 mentioned the following contract information:
81
82 @emph{This report describes research done at the Artificial
83 Intelligence Laboratory of the Massachusetts Institute of Technology.
84 Support for the laboratory's artificial intelligence research is
85 provided in part by the Advanced Research Projects Agency of the
86 Department of Defense under Office of Naval Research contract
87 N00014-85-K-0124.}
88
89 The appendix includes Jonathan Amsterdam's Working Paper 324,
90 MIT AI Lab entitled ``Don't Loop, Iterate.''
91 @end quotation
92 @end copying
93 @c %**end of header
94
95 @titlepage
96 @title The Iterate Manual and Paper
97 @c @subtitle Version X.X
98 @c @author Jonathan Amsterdam
99
100 @page
101 @vskip 0pt plus 1filll
102 @insertcopying
103 @end titlepage
104
105 @contents
106
107 @ifnottex
108 @node Top
109 @top iterate
110 @insertcopying
111 @end ifnottex
112
113 @menu
114 * Introduction::
115 * Clauses::
116 * Other Features::
117 * Types and Declarations::
118 * Problems with Code Movement::
119 * Differences Between Iterate and Loop::
120 * Rolling Your Own::
121 * Non-portable Extensions to Iterate (Contribs)::
122 * Obtaining Iterate::
123 * Acknowledgements::
124 * Don't Loop Iterate::
125 * Comprehensive Index::
126 @end menu
127
128 @c ===================================================================
129 @node Introduction
130 @chapter Introduction
131
132 This manual describes @iter{}, a powerful iteration facility for
133 Common Lisp. @iter{} provides abstractions for many common iteration
134 patterns and allows for the definition of additional patterns.
135 @iter{} is a macro that expands into ordinary Lisp at compile-time, so
136 it is more efficient than higher-order functions like @code{map} and
137 @code{reduce}. While it is similar to @code{loop}, @iter{} offers a
138 more Lisp-like syntax and enhanced extensibility. (For a more
139 complete comparison of @iter{} with other iteration constructs, see
140 @acronym{MIT} @acronym{AI} Lab Working Paper No.@: 324, @emph{Don't
141 Loop, Iterate.} also included in this manual in @ref{Don't Loop
142 Iterate}.)
143
144 An @iter{} form consists of the symbol @code{iter}@footnote{You can
145 also use @code{iterate}, but @code{iter} is preferred because it
146 avoids potential conflicts with possible future additions to Common
147 Lisp, and because it saves horizontal space when writing code.}
148 followed by one or more forms, some of which may be @iter{}
149 @emph{clauses}. Here is a simple example of @iter{} which collects
150 the numbers from 1 to 10 into a list, and returns the list. The
151 return value is shown following the arrow.
152
153 @lisp
154 (iter (for i from 1 to 10)
155 (collect i)) @result{} (1 2 3 4 5 6 7 8 9 10)
156 @end lisp
157
158 This form contains two clauses: a @code{for} clause that steps the
159 variable @code{i} over the integers from 1 to 10, and a @code{collect}
160 clause that accumulates its argument into a list. With a few
161 exceptions, all @iter{} clauses have the same format: alternating
162 symbols (called @emph{keywords}) and expressions (called
163 @emph{arguments}). The syntax and terminology are those of Common
164 Lisp's keyword lambda lists. One difference is that @iter{}'s keywords
165 do not have to begin with a colon---though they may, except for the
166 first symbol of a clause. So you can also write @code{(for i :from 1
167 :to 10)} if you prefer.
168
169 Any Lisp form can appear in the body of an @iter{}, where it will have
170 its usual meaning. @iter{} walks the entire body, expanding macros,
171 and recognizing clauses at any level. This example collects all the
172 odd numbers in a list:
173
174 @lisp
175 (iter (for el in list)
176 (if (and (numberp el) (oddp el))
177 (collect el)))
178 @end lisp
179
180 There are clauses for iterating over numbers, lists, arrays and other
181 objects, and for collecting, summing, counting, maximizing and other
182 useful operations. @iter{} also supports the creation of new variable
183 bindings, stepping over multiple sequences at once, destructuring, and
184 compiler declarations of variable types. The following example
185 illustrates some of these features:
186
187 @lisp
188 (iter (for (key . item) in alist)
189 (for i from 0)
190 (declare (fixnum i))
191 (collect (cons i key)))
192 @end lisp
193
194 This loop takes the keys of an alist and returns a new alist
195 associating the keys with their positions in the original list. The
196 compiler declaration for @code{i} will appear in the generated code in
197 the appropriate place.
198
199 @c ===================================================================
200 @node Clauses
201 @chapter Clauses
202
203 Most of @iter{}'s clauses will be familiar to @code{loop} programmers.
204 (@code{loop} is an iteration macro that has been incorporated into
205 Common Lisp. See Guy Steele's @emph{Common Lisp, 2nd Edition}.) In
206 nearly all cases they behave the same as their @code{loop}
207 counterparts, so a @code{loop} user can switch to @iter{} with little
208 pain (and much gain).
209
210 All clauses with the standard keyword-argument syntax consist of two
211 parts: a @emph{required} part, containing keywords that must be present and
212 in the right order; and an @emph{optional} part, containing keywords that
213 may be omitted and, if present, may occur in any order. In the
214 descriptions below, the parts are separated by the Lisp lambda-list
215 keyword @code{&optional}.
216
217 @menu
218 * Drivers::
219 * Variable Binding and Setting::
220 * Gathering Clauses::
221 * Control Flow::
222 * Predicates::
223 * Code Placement::
224 @end menu
225
226 @c ===================================================================
227 @node Drivers
228 @section Drivers
229
230 An iteration-driving clause conceptually causes the iteration to go
231 forward. Driver clauses in @iter{} allow iteration over numbers,
232 lists, vectors, hashtables, packages, files and streams.
233 Iteration-driving clauses must appear at the top level of an @iter{}
234 form; they cannot be nested inside another clause. The driver
235 variable is updated at the point where the driver clause occurs.
236 Before the clause is executed for the first time, the value of the
237 variable is undefined.
238
239 @c Also, regardless of where the driver clause appears in the body,
240 @c the driver variable is stepped at the top of the loop; hence it is
241 @c stylistically preferable, though not required, to place driver
242 @c clauses at the beginning of the @iter{}.
243
244 Multiple drivers may appear in a single @iter{} form, in which case all
245 of the driver variables are updated each time through the loop, in the
246 order in which the clauses appear. The first driver to terminate will
247 terminate the entire loop.
248
249 In all cases, the value of the driver variable on exit from the loop,
250 including within the epilogue code (see the @code{finally} clause), is
251 undefined.
252
253 All the parameters of a driver clause are evaluated once, before the
254 loop begins. Hence it is not possible to change the bounds or other
255 properties of an iteration by side-effect from within the loop.
256
257 With one exception, driver clauses begin with the word @code{for} (or
258 the synonym @code{as}) and mention an iteration variable, which is
259 given a binding within the @iter{} form. The exception is
260 @code{repeat}, which just executes a loop a specified number of times:
261
262 @clauseu{repeat}
263 @deffn Clause repeat @v{n}
264
265 Repeat the loop @var{n} times. For example:
266
267 @lisp
268 (iter (repeat 100)
269 (print "I will not talk in class."))
270 @end lisp
271
272 If @mathx{n \leq 0, n <= 0}, then loop will never be executed. If @var{n} is
273 not an integer, the actual number of executions will be @mathx{\lceil n
274 \rceil, ceil(n)}.
275 @end deffn
276
277 @menu
278 * Numerical Iteration::
279 * Sequence Iteration::
280 * Generalized Drivers::
281 * Generators::
282 * Previous Values of Driver Variables::
283 @end menu
284
285 @c ===================================================================
286 @node Numerical Iteration
287 @subsection Numerical Iteration
288
289 @clauseu{for}
290 @deffn Clause for @v{var} @k{&sequence}
291
292 The general form for iterating over a sequence of numbers requires a
293 variable and, optionally, one or more keywords that provide the bounds
294 and step size of the iteration. The @code{&sequence} lambda-list
295 keyword is a shorthand for these sequence keywords. They are:
296 @code{from}, @code{upfrom}, @code{downfrom}, @code{to}, @code{downto},
297 @code{above}, @code{below} and @code{by}. @code{from} provides the
298 starting value for @var{var} and defaults to zero. @code{to} provides
299 a final value and implies that the successive values of @var{var} will
300 be increasing; @code{downto} implies that they will be decreasing.
301 The loop terminates when @var{var} passes the final value
302 (i.e.@: becomes smaller or larger than it, depending on the direction of
303 iteration); in other words, the loop body will never be executed for
304 values of @var{var} past the final value. @code{below} and
305 @code{above} are similar to @code{to} and @code{downto}, except that
306 the loop terminates when @var{var} equals or passes the final value.
307
308 If no final value is specified, the variable will be stepped forever.
309 Using @code{from} or @code{upfrom} will result in increasing values,
310 while @code{downfrom} will give decreasing values.
311
312 On each iteration, @var{var} is incremented or decremented by the
313 value of the sequence keyword @code{by}, which defaults to 1. It
314 should always be a positive number, even for downward iterations.
315
316 In the following examples, the sequence of numbers generated is shown
317 next to the clause.
318
319 @lisp
320 (for i upfrom 0) @result{} 0 1 2 @dots{}
321 (for i from 5) @result{} 5 6 7 @dots{} ; either from or upfrom is okay
322 (for i downfrom 0) @result{} 0 -1 -2 @dots{}
323 (for i from 1 to 3) @result{} 1 2 3
324 (for i from 1 below 3) @result{} 1 2
325 (for i from 1 to 3 by 2) @result{} 1 3
326 (for i from 1 below 3 by 2) @result{} 1
327 (for i from 5 downto 3) @result{} 5 4 3
328 @end lisp
329 @end deffn
330
331 @c ===================================================================
332 @node Sequence Iteration
333 @subsection Sequence Iteration
334
335 There are a number of clauses for iterating over sequences. In all of
336 them, the argument following @code{for} may be a list instead of a
337 symbol, in which case destructuring is performed. See
338 @ref{Destructuring}.
339
340 @claused{for, in}
341 @deffn Clause for @v{var} @cl{in} @v{list} @k{&optional} @k{by} @v{step-function}
342
343 @var{var} is set to successive elements of list. @var{step-function},
344 which defaults to @code{cdr}, is used to obtain the next sublist.
345
346 This clause uses @code{endp} to test for the end of a list, hence
347 should signal an error when processing an improper list whose final
348 @code{cdr} is not @code{nil}---like @code{loop}. Prior to 2007,
349 @iter{} would default to @code{atom} and silently exit.
350
351 @vindex *list-end-test*
352 @quotation Compatibility Note
353 The original implementation used the variable
354 @code{iterate::*list-end-test*}, defaulting to @code{atom}. Years
355 later, it was deemed unacceptable for the semantics @emph{not} to be
356 lexically apparent from the iteration form so this variable was
357 removed. If your application depends on the original behaviour, the
358 ancient @code{for @v{var} in} is equivalent to
359 @code{for (@v{var}) on}.
360 @end quotation
361 @end deffn
362
363 @claused{for, on}
364 @deffn Clause for @v{var} @cl{on} @v{list} @k{&optional} @k{by} @v{step-function}
365
366 @var{var} is set to successive sublists of list. @var{step-function}
367 (default @code{cdr}) is used as in @code{for@dots{} in}.
368
369 This clause uses @code{atom} to test for the end of a list, so it can
370 be used with dotted lists---like @code{loop}.
371 @end deffn
372
373 @c These two clauses use @code{atom} to test for the end of a list.
374 @c Hence, given a list whose final @code{cdr} is not @code{nil}, they
375 @c will silently ignore the last @code{cdr}. Other choices are
376 @c @code{endp}, which would signal an error, and @code{null}, which would
377 @c probably result in an error somewhere else. If you wish to use an
378 @c end-test other than @code{atom}, set the variable
379 @c @code{iterate::*list-end-test*} to the name of the desired function.
380
381 @claused{for, in-vector}
382 @deffn Clause for @v{var} @cl{in-vector} @v{vector} @k{&sequence}
383
384 @var{var} takes on successive elements from @var{vector}. The vector's
385 fill-pointer is observed. Here and in subsequent clauses, the
386 @code{&sequence} keywords include @code{with-index}, which takes a
387 symbol as argument and uses it for the index variable instead of an
388 internally generated symbol. The other @code{&sequence} keywords
389 behave as in numerical iteration, except that the default iteration
390 bounds are the bounds of the vector. E.g.@: in @code{(for i in-vector v
391 downto 3)}, @code{i} will start off being bound to the last element in
392 @code{v}, and will be set to preceding elements down to and including
393 the element with index 3.
394 @end deffn
395
396 @claused{for, in-sequence}
397 @deffn Clause for @v{var} @cl{in-sequence} @v{seq} @k{&sequence}
398
399 This uses Common Lisp's generalized sequence functions, @code{elt} and
400 @code{length}, to obtain elements and determine the length of
401 @var{seq}. Hence it will work for any sequence, including lists, and
402 will observe the fill-pointers of vectors.
403 @end deffn
404
405 @claused{for, in-string}
406 @deffn Clause for @v{var} @cl{in-string} @v{string} @k{&sequence}
407
408 @var{var} is set to successive characters of @var{string}.
409 @end deffn
410
411 @claused{for, index-of-vector}
412 @claused{for, index-of-sequence}
413 @claused{for, index-of-string}
414 @deffn Clause for @v{var} @cl{index-of-vector} @v{vector} @k{&sequence}
415 @deffnx Clause for @v{var} @cl{index-of-sequence} @v{sequence} @k{&sequence}
416 @deffnx Clause for @v{var} @cl{index-of-string} @v{string} @k{&sequence}
417
418 @var{var} is set to successive indices of the sequence. These clauses
419 avoid the overhead of accessing the sequence elements for those
420 applications where they do not need to be examined, or are examined
421 rarely. They admit all the optional keywords of the other sequence
422 drivers except the (redundant) @code{with-index} keyword.
423 @end deffn
424
425 @claused{for, in-hash-table}
426 @claused{for, in-hashtable}
427 @deffn Clause for (@v{key} @v{value}) @cl{in-hash-table} @v{table}
428 @deffnx Clause for (@v{key} @v{value}) @cl{in-hashtable} @v{table}
429
430 @var{key} and @var{value}, which must appear as shown in a list and
431 may be destructuring templates, are set to the keys and values of
432 @var{table}. If @var{key} is @code{nil}, then the hash-table's keys
433 will be ignored; similarly for @var{value}. The order in which
434 elements of @var{table} will be retrieved is unpredictable.
435 The two versions, @var{in-hash-table} or @var{in-hashtable}, are
436 equivalent, with the same semantics.
437 @end deffn
438
439 @claused{for, in-package}
440 @deffn Clause for @v{var} @cl{in-package} @v{package} @
441 @k{&optional} @k{external-only} @v{ext}
442
443 Iterates over all the symbols in @var{package}, or over only the
444 external symbols if @var{ext} is specified and non-@code{nil}.
445 @var{ext} is not evaluated. The same symbol may appear more than
446 once.
447 @end deffn
448
449 @claused{for, in-packages}
450 @deffn Clause for @v{var} @cl{in-packages} @
451 @k{&optional} @k{having-access} @v{symbol-types}
452
453 Iterates over all the symbols from the list of packages denoted by the
454 descriptor @var{packages} and having accessibility (or visibility)
455 given by @var{symbol-types}. This defaults to the list
456 @code{(:external :internal :inherited)} and is not evaluated.
457 @var{var} must be a list of up to three variables: in each iteration,
458 these will be set to a symbol, its access-type and package (as per
459 @code{with-package-iterator} in ANSI CL). The same symbol may appear
460 more than once.
461 @end deffn
462
463 @claused{for, in-file}
464 @deffn Clause for @v{var} @cl{in-file} @v{name} @
465 @k{&optional} @k{using} @v{reader}
466
467 Opens the file @var{name} (which may be a string or pathname) for
468 input, and iterates over its contents. @var{reader} defaults to
469 @code{read}, so by default @emph{var} will be bound to the successive
470 forms in the file. The @iter{} body is wrapped in an
471 @code{unwind-protect} to ensure that the file is closed no matter how
472 the @iter{} is exited.
473 @end deffn
474
475 @claused{for, in-stream}
476 @deffn Clause for @v{var} @cl{in-stream} @v{stream} @k{&optional} @k{using} @
477 @v{reader}
478
479 Like @code{for@dots{} in-file}, except that @var{stream} should be an
480 existing stream object that supports input operations.
481 @end deffn
482
483 @c ===================================================================
484 @node Generalized Drivers
485 @subsection Generalized Drivers
486
487 These are primarily useful for writing drivers that can also be used
488 as generators (see @ref{Generators}).
489
490 @clauseu{terminate}
491 @claused{for, next}
492 @deffn Clause for @v{var} @cl{next} @v{expr}
493
494 @var{var} is set to @var{expr} each time through the loop.
495 Destructuring is performed. When the clause is used as a generator,
496 @var{expr} is the code that is executed when @code{(next @emph{var})}
497 is encountered (see @ref{Generators}). @var{expr} should compute the
498 first value for @var{var}, as well as all subsequent values, and is
499 responsible for terminating the loop. For compatibility with future
500 versions of @iter{}, this termination should be done with
501 @code{terminate}, which can be considered a synonym for @code{finish}
502 (see @ref{Control Flow}).
503
504 As an example, the following clauses are equivalent to @code{(for i
505 from 1 to 10)}:
506
507 @lisp
508 (initially (setq i 0))
509 (for i next (if (> i 10) (terminate) (incf i)))
510 @end lisp
511 @end deffn
512
513 @claused{for, do-next}
514 @deffn Clause for @v{var} @k{do-next} @v{form}
515
516 @var{form} is evaluated each time through the loop. Its value is
517 @var{not} set to @var{var}; that is @var{form}'s job. @var{var} is
518 only present so that @iter{} knows it is a driver variable. @*
519 @code{(for @var{var} next @var{expr})} is equivalent to @code{(for
520 @var{var} do-next (dsetq @var{var} @var{expr}))}. (See
521 @ref{Destructuring} for an explanation of @code{dsetq}.)
522 @end deffn
523
524 @c ===================================================================
525 @node Generators
526 @subsection Generators
527
528 In all of the above clauses, the driver variable is updated on each
529 iteration. Sometimes it is desirable to have greater control over
530 updating. For instance, consider the problem of associating numbers,
531 in increasing order and with no gaps, with the non-@code{nil} elements
532 of a list. One obvious first pass at writing this is:
533
534 @lisp
535 (iter (for el in list)
536 (for i upfrom 1)
537 (if el (collect (cons el i))))
538 @end lisp
539
540 But on the list @code{(a b nil c)} this produces @code{((a . 1) (b
541 . 2) (c . 4))} instead of the desired @code{((a . 1) (b . 2) (c
542 . 3))}. The problem is that @code{i} is incremented each time through
543 the loop, even when @code{el} is @code{nil}.
544
545 The problem could be solved elegantly if we could step @code{i} only
546 when we wished to. This can be accomplished for any @iter{} driver by
547 writing @code{generate} (or its synonym @code{generating}) instead of
548 @code{for}. Doing so produces a @emph{generator}---a driver whose
549 values are yielded explicitly. To obtain the next value of a
550 generator variable @var{v}, write @code{(next @var{v})}. The value of
551 a @code{next} form is the next value of @emph{v}, as determined by its
552 associated driver clause. @code{next} also has the side-effect of
553 updating @var{v} to that value. If there is no next value,
554 @code{next} will terminate the loop, just as with a normal driver.
555
556 Using generators, we can now write our example like this:
557
558 @lisp
559 (iter (for el in list)
560 (generate i upfrom 1)
561 (if el (collect (cons el (next i)))))
562 @end lisp
563
564 Now @code{i} is updated only when @code{(next i)} is executed, and
565 this occurs only when @code{el} is non-@code{nil}.
566
567 To better understand the relationship between ordinary drivers and
568 generators, observe that we can rewrite an ordinary driver using its
569 generator form immediately followed by @code{next}, as this example
570 shows:
571
572 @lisp
573 (iter (generating i from 1 to 10)
574 (next i)
575 @dots{})
576 @end lisp
577
578 Provided that the loop body contains no @code{(next i)} forms, this
579 will behave just as if we had written @code{(for i from 1 to 10)}.
580
581 We can still refer to a driver variable @var{v} without using
582 @code{next}; in this case, its value is that given to it by the last
583 evaluation of @code{(next @var{v})}. Before @code{(next @var{v})} has
584 been called the first time, the value of @var{v} is undefined.
585
586 This semantics is more flexible than one in which @var{v} begins the
587 loop bound to its first value and calls of @code{next} supply
588 subsequent values, because it means the loop will not terminate too
589 soon if the generator's sequence is empty. For instance, consider the
590 following code, which tags non-@code{nil} elements of a list using a
591 list of tags, and also counts the null elements. (We assume there are
592 at least as many tags as non-@code{nil} elements.)
593
594 @lisp
595 (let* ((counter 0)
596 (tagged-list (iter (for el in list)
597 (generating tag in tag-list)
598 (if (null el)
599 (incf counter)
600 (collect (cons el (next tag)))))))
601 @dots{})
602 @end lisp
603
604 It may be that there are just as many tags as non-null elements of
605 @code{list}. If all the elements of @code{list} are null, we still
606 want the counting to proceed, even though @code{tag-list} is
607 @code{nil}. If @code{tag} had to be assigned its first value before
608 the loop begins, we would have had to terminate the loop before the
609 first iteration, since when @code{tag-list} is @code{nil}, @code{tag}
610 has no first value. With the existing semantics, however, @code{(next
611 tag)} will never execute, so the iteration will cover all the elements
612 of @code{list}.
613
614 When the ``variable'' of a driver clause is actually a destructuring
615 template containing several variables, all the variables are eligible
616 for use with @code{next}. As before, @code{(next @var{v})} evaluates
617 to @var{v}'s next value; but the effect is to update all of the
618 template's variables. For instance, the following code will return
619 the list @code{(a 2 c)}.
620
621 @lisp
622 (iter (generating (key . item) in '((a . 1) (b . 2) (c . 3)))
623 (collect (next key))
624 (collect (next item)))
625 @end lisp
626
627 Only driver clauses with variables can be made into generators. This
628 includes all clauses mentioned so far except for @code{repeat}. It
629 does @emph{not} include @code{for@dots{} previous}, @code{for@dots{}
630 =}, @code{for@dots{} initially@dots{} then} or @code{for@dots{}
631 first@dots{} then} (see below).
632
633 @c ===================================================================
634 @node Previous Values of Driver Variables
635 @subsection Previous Values of Driver Variables
636
637 Often one would like to access the value of a variable on a previous
638 iteration. @iter{} provides a special clause for accomplishing this.
639
640 @claused{for, previous}
641 @deffn Clause for @v{pvar} @cl{previous} @v{var} @
642 @k{&optional} @k{initially} @v{init} @k{back} @v{n}
643
644 Sets @var{pvar} to the previous value of @var{var}, which should be a
645 driver variable, a variable from another @code{for@dots{} previous}
646 clause, or a variable established by a @code{for@dots{} =},
647 @code{for@dots{} initially@dots{} then} or @code{for@dots{}
648 first@dots{} then} clause (see @ref{Variable Binding and Setting}).
649 Initially, @var{pvar} is given the value @var{init} (which defaults to
650 @code{nil}). The @var{init} expression will be moved outside the loop
651 body, so it should not depend on anything computed within the loop.
652 @var{pvar} retains the value of @var{init} until @var{var} is set to
653 its second value, at which point @var{pvar} is set to @var{var}'s
654 first value; and so on.
655
656 The argument @var{n} to @code{back} must be a constant, positive
657 integer, and defaults to 1. It determines how many iterations back
658 @var{pvar} should track @var{var}. For example, when @var{n} is 2,
659 then @var{pvar} will be assigned @var{var}'s first value when
660 @var{var} is set to its third value.
661
662 A @code{for@dots{} previous} clause may occur after or before its
663 associated driver clause. @code{for@dots{} previous} works with
664 generators as well as ordinary drivers.
665
666 Example:
667
668 @lisp
669 (iter (for el in '(1 2 3 4))
670 (for p-el previous el)
671 (for pp-el previous p-el initially 0)
672 (collect pp-el))
673 @end lisp
674
675 This evaluates to @code{(0 0 1 2)}. It could have been written more
676 economically as
677
678 @lisp
679 (iter (for el in '(1 2 3 4))
680 (for pp-el previous el back 2 initially 0)
681 (collect pp-el))
682 @end lisp
683 @end deffn
684
685 @c ===================================================================
686 @node Variable Binding and Setting
687 @section Variable Binding and Setting
688
689 Several clauses exist for establishing new variable bindings or for
690 setting variables in the loop. They all support destructuring.
691
692 @clauseu{with}
693 @deffn Clause with @v{var} @k{&optional} @k{=} @v{value}
694
695 Causes @var{var} to be bound to value before the loop body is entered.
696 If @var{value} is not supplied, @var{var} assumes a default binding,
697 which will be @code{nil} in the absence of declarations. Also, if
698 @var{value} is not supplied, no destructuring is performed; instead,
699 @var{var} may be a list of symbols, all of which are given default
700 bindings. If @var{value} is supplied, @var{var} is bound to it, with
701 destructuring.
702
703 Because @code{with} creates bindings whose scope includes the entire
704 @iter{} form, it is good style to put all @code{with} clauses at the
705 beginning.
706
707 Successive occurrences of @code{with} result in sequential bindings
708 (as with @code{let*}). There is no way to obtain parallel bindings;
709 see @ref{Parallel Binding and Stepping} for a rationale.
710 @end deffn
711
712 @claused{for, =}
713 @deffn Clause for @v{var} @cl{=} @v{expr}
714
715 On each iteration, @var{expr} is evaluated and @var{var} is set to its
716 value.
717
718 This clause may appear to do the same thing as @code{for@dots{} next}.
719 In fact, they are quite different. @code{for@dots{} =} provides only
720 three services: it sets up a binding for @var{var}, sets it to
721 @var{expr} on each iteration, and makes it possible to use
722 @code{for@dots{} previous} with @var{var}. @code{for@dots{} next}
723 provides these services in addition to the ability to turn the driver
724 into a generator.
725
726 @c Also, the code which sets @var{var} appears in the loop body in the
727 @c same place as the @code{for@dots{} =} clause; the code for
728 @c @code{for@dots{} next} appears at the top of the loop, as with
729 @c other drivers (except when being used as a generator).
730 @end deffn
731
732 @clauset{for, initially, then}
733 @deffn Clause for @v{var} @cl{initially} @v{init-expr} @cl{then} @v{then-expr}
734
735 Before the loop begins, @var{var} is set to @var{init-expr;} on all
736 iterations after the first it is set to @var{then-expr.} This clause
737 must occur at top-level. @var{init-expr} will be moved outside the
738 loop body and @var{then-expr} will be moved to the end of the loop
739 body, so they are subject to code motion problems (see @ref{Problems
740 with Code Movement}).
741
742 This clause may appear to be similar to @code{for@dots{} next}, but in
743 fact they differ significantly. @code{for@dots{} initially@dots{}
744 then} is typically used to give @var{var} its first value before the
745 loop begins, and subsequent values on following iterations. This is
746 incompatible with generators, whose first value and subsequent values
747 must all be computed by @code{(next @var{var})}. Also, the update of
748 @var{var} in @code{for@dots{} initially@dots{} then} does not occur at
749 the location of the clause.
750
751 Use @code{for@dots{} initially@dots{} then} for one-shot computations
752 where its idiom is more convenient, but use @code{for@dots{} next} for
753 extending @iter{} with new drivers (see @ref{Rolling Your Own}).
754 @end deffn
755
756 @clauset{for, first, then}
757 @deffn Clause for @v{var} @cl{first} @v{first-expr} @cl{then} @v{then-expr}
758
759 The first time through the loop, @var{var} is set to @var{first-expr};
760 on subsequent iterations, it is set to @var{then-expr}. This differs
761 from @code{for@dots{} initially} in that @var{var} is set to
762 @var{first-expr} inside the loop body, so @var{first-expr} may depend
763 on the results of other clauses. For instance,
764
765 @lisp
766 (iter (for num in list)
767 (for i first num then (1+ i))
768 ...)
769 @end lisp
770
771 will set @code{i} to the first element of @code{list} on the first
772 iteration, whereas
773
774 @lisp
775 (iter (for num in list)
776 (for i initially num then (1+ i))
777 ...)
778 @end lisp
779
780 is probably erroneous; @code{i} will be bound to @code{num}'s default
781 binding (usually @code{nil}) for the first iteration.
782 @end deffn
783
784 @quotation Compatibility Note
785 @code{loop}'s @code{for@dots{} =} works like @iter{}'s, but
786 @code{loop} used the syntax @code{for@dots{} =@dots{} then} to mean
787 @code{for@dots{} initially@dots{} then}. It was felt that these two
788 operations were sufficiently different to warrant different keywords.
789
790 Also, the @code{for} in the above three clauses is misleading, since
791 none is true driver (e.g.@: none has a corresponding @code{generate}
792 form). @code{setting} would have been a better choice, but @code{for}
793 was used to retain some compatibility with @code{loop}.
794 @end quotation
795
796 @c ===================================================================
797 @node Gathering Clauses
798 @section Gathering Clauses
799
800 Many of @iter{}'s clauses accumulate values into a variable, or set a
801 variable under certain conditions. At the end of the loop, this
802 variable contains the desired result. All these clauses have an
803 optional @code{into} keyword, whose argument should be a symbol. If
804 the @code{into} keyword is not supplied, the accumulation variable
805 will be internally generated and its value will be returned at the end
806 of the loop; if a variable is specified, that variable is used for the
807 accumulation, and is not returned as a result---it is up to the user
808 to return it explicitly, in the loop's epilogue code (see
809 @code{finally}). It is safe to examine the accumulation variable
810 during the loop, but it should not be modified.
811
812 These clauses all begin with a verb. When the verb does not conflict
813 with an existing Common Lisp function, then it may be used in either
814 its infinitival or present-participle form (e.g.@: @code{sum},
815 @code{summing}). However, when there is a conflict with Common Lisp,
816 only the present-participle form may be used (e.g.@: @code{unioning}).
817 This is to prevent @iter{} clauses from clashing with Common Lisp
818 functions.
819
820 @c although these clauses are described as ``producing a value,'' it
821 @c is a mistake to think of the lisp list representing the clause as a
822 @c value-producing form in the usual way. clauses may legally be
823 @c written where a value is expected, e.g.@: @code{(setq x (sum i))},
824 @c but the lisp value of a clause in such a context is undefined.
825
826 @menu
827 * Reductions::
828 * Accumulations::
829 * Finders::
830 * Aggregated Boolean Tests::
831 @end menu
832
833 @c ===================================================================
834 @node Reductions
835 @subsection Reductions
836
837 @emph{Reduction} is an extremely common iteration pattern in which the
838 results of successive applications of a binary operation are
839 accumulated. For example, a loop that computes the sum of the
840 elements of a list is performing a reduction with the addition
841 operation. This could be written in Common Lisp as @code{(reduce #'+
842 list)} or with @iter{} as
843
844 @lisp
845 (iter (for el in list)
846 (sum el))
847 @end lisp
848
849 @clauseu{sum}
850 @deffn Clause sum @v{expr} @k{&optional} @k{into} @v{var}
851 @k{result-type} @v{type}
852
853 Each time through the loop, @var{expr} is evaluated and added to a
854 variable, which is bound initially to zero. If @var{expr} has a type,
855 it is @emph{not} used as the type of the sum variable. Unless
856 @var{type} is supplied or @var{var} has a declared type, @var{var} will
857 always have type @code{number}. To get the result variable to be of a
858 more specific type, either supply @var{type}, as in:
859
860 @lisp
861 (iter (for el in number-list)
862 (sum el result-type fixnum))
863 @end lisp
864
865 or use an explicit variable, as in:
866
867 @lisp
868 (iter (for el in number-list)
869 (sum el into x)
870 (declare (fixnum x))
871 (finally (return x)))
872 @end lisp
873 @end deffn
874
875 @clauseu{multiply}
876 @deffn Clause multiply @v{expr} @k{&optional} @k{into} @v{var}
877 @k{result-type} @v{type}
878
879 Like @code{sum}, but the initial value of the result variable is
880 @math{1}, and the variable is updated by multiplying @var{expr} into
881 it.
882 @end deffn
883
884 @clauseu{counting}
885 @deffn Clause counting @v{expr} @k{&optional} @k{into} @v{var}
886 @k{result-type} @v{type}
887
888 @var{expr} is evaluated on each iteration. If it is non-@code{nil},
889 the accumulation variable, initially zero, is incremented.
890 @end deffn
891
892 @clauseu{maximize}
893 @clauseu{minimize}
894 @deffn Clause maximize @v{expr} @k{&optional} @k{into} @v{var}
895 @deffnx Clause minimize @v{expr} @k{&optional} @k{into} @v{var}
896
897 @var{expr} is evaluated on each iteration and its extremum (maximum or
898 minimum) is stored in the accumulation variable. If @var{expr} is
899 never evaluated, then the result is @code{nil} (if the accumulation
900 variable is untyped) or @math{0} (if it has a numeric type).
901 @end deffn
902
903 @clauseu{reducing}
904 @deffn Clause reducing @v{expr} @k{by} @v{func} @k{&optional}
905 @k{initial-value} @v{init-val} @k{into} @v{var}
906 @k{result-type} @v{type}
907
908 This is a general way to perform reductions. @var{func} should be a
909 function of two arguments, the first of which will be the value
910 computed so far and the second of which will be the value of
911 @var{expr}. It should return the new value. @code{reducing} is
912 roughly equivalent to the Common Lisp @code{(reduce @var{func}
913 @var{sequence} :key @var{expr-function})}, where @var{expr-function}
914 is used to derive values from the successive elements of
915 @var{sequence}.
916
917 If the @code{reducing} clause is never executed, the result is
918 undefined.
919
920 It is not necessary to provide an initial value, but better code can
921 be generated if one is supplied. Regardless of its location in the
922 @iter{} body, @var{init-val} will be evaluated before the loop is
923 entered, so it should not depend on any value computed inside the
924 @iter{} form.
925
926 @c if a @var{var} is not specified, you can get @iter{} to declare the
927 @c type of the internal variable by putting a @code{the} expression
928 @c around @var{func}. see @ref{Types}.
929 @end deffn
930
931 @c @impnote{in principle, |maximize| and |minimize| can be thought of
932 @c as reductions where the initial value is the smallest (or largest)
933 @c value that the accumulation variable can assume. because lisp's
934 @c bignums can represent arbitrary integers, these clauses cannot be
935 @c implemented as reductions in general. if, however, the type of
936 @c ~expr~ or ~var~ can be determined to be a fixnum or a float,
937 @c @iter{} will implement the clause as a true reduction, using one of
938 @c the constants |most-negative-fixnum|, |@c most-positive-fixnum|,
939 @c |most-negative-short-float|, etc.@: as appropriate.}
940
941 @c ===================================================================
942 @node Accumulations
943 @subsection Accumulations
944
945 All the predefined accumulation clauses add values to a sequence. If
946 the sequence is a list, they all have the property that the partial
947 list is kept in the correct order and available for inspection at any
948 point in the loop.
949
950 @clauseu{collect}
951 @deffn Clause collect @v{exptr} @k{&optional}
952 @k{into} @v{var} @k{at} @v{place} @k{result-type} @v{type}
953
954 Produces a sequence of the values of @var{exptr} on each
955 iteration. @var{place} indicates where the next value of @var{exptr}
956 is added to the list and may be one of the symbols @code{start},
957 @code{beginning} (a synonym for @code{start}) or @code{end}. The
958 symbol may be quoted, but need not be. The default is @code{end}.
959 For example,
960
961 @lisp
962 (iter (for i from 1 to 5)
963 (collect i))
964 @end lisp
965
966 produces @code{(1 2 3 4 5)}, whereas
967
968 @lisp
969 (iter (for i from 1 to 5)
970 (collect i at beginning))
971 @end lisp
972
973 produces @code{(5 4 3 2 1)} (and is likely to be faster in most Common
974 Lisp implementations).
975
976 If @var{type} is provided, it should be a subtype of @code{sequence}.
977 The default is @code{list}. Specifying a type other than @code{list}
978 will result in @code{collect} returning a sequence of that type.
979 @emph{However}, the type of the sequence being constructed when inside
980 the loop body is undefined when a non-@code{list} type is specified.
981 (As with @var{place}, quoting @var{type} is optional.)
982 @end deffn
983
984 @clauseu{adjoining}
985 @deffn Clause adjoining @v{exptr} @k{&optional} @k{into} @v{var} @
986 @k{test} @v{test} @k{at} @v{place} @
987 @k{result-type} @v{type}
988
989 Like @code{collect}, but only adds the value of @var{exptr} if it is
990 not already present. @var{test}, which defaults to @code{#'eql}, is
991 the test to be used with @code{member}.
992 @end deffn
993
994 @clauseu{appending}
995 @clauseu{nconcing}
996 @clauseu{unioning}
997 @clauseu{nunioning}
998 @deffn Clause appending @v{expr} @k{&optional} @k{into} @v{var} @k{at} @v{place}
999 @deffnx Clause nconcing @v{expr} @k{&optional} @k{into} @v{var} @k{at} @v{place}
1000 @deffnx Clause unioning @v{expr} @k{&optional} @k{into} @v{var} @
1001 @k{test} @v{test} @k{at} @v{place}
1002 @deffnx Clause nunioning @v{expr} @k{&optional} @k{into} @v{var} @
1003 @k{test} @v{test} @k{at} @v{place}
1004
1005 These are like @code{collect}, but behave like the Common Lisp
1006 functions @code{append}, @code{nconc}, @code{union} or @code{nunion}.
1007 As in Common Lisp, they work only on lists. Also as in Common Lisp,
1008 @code{unioning} and @code{nunioning} assume that the value of
1009 @var{expr} contains no duplicates.
1010 @end deffn
1011
1012 @clauseu{accumulate}
1013 @deffn Clause accumulate @v{expr} @k{by} @v{func} @k{&optional} @
1014 @k{initial-value} @v{init-val} @k{into} @v{var}
1015
1016 This is a general-purpose accumulation clause. @var{func} should be a
1017 function of two arguments, the value of @var{expr} and the value
1018 accumulated so far in the iteration, and it should return the updated
1019 value. If no initial value is supplied, @code{nil} is used.
1020
1021 @c If a @var{var} is not specified, you can get @iter{} to declare the
1022 @c type of the internal variable by putting a @code{the} expression
1023 @c around @var{func}. see section \ref{types}.
1024
1025 The differences between @code{accumulate} and @code{reducing} are
1026 slight. One difference is that the functions take their arguments in
1027 a different order. Another is that in the absence of @var{init-val},
1028 @code{accumulate} will use @code{nil}, whereas @code{reducing} will
1029 generate different code that avoids any dependence on the initial
1030 value. The reason for having both clauses is that one usually thinks
1031 of reductions (like @code{sum}) and accumulations (like
1032 @code{collect}) as different beasts.
1033 @end deffn
1034
1035 @c ===================================================================
1036 @node Finders
1037 @subsection Finders
1038
1039 A @emph{finder} is a clause whose value is an expression that meets
1040 some condition.
1041
1042 @claused{finding, such-that}
1043 @deffn Clause finding @var{expr} @cl{such-that} @v{test} @k{&optionally} @
1044 @k{into} @v{var} @k{on-failure} @v{failure-value}
1045
1046 If @var{test} (which is an expression) ever evaluates to
1047 non-@code{nil}, the loop is terminated, the epilogue code is run and
1048 the value of @var{expr} is returned. Otherwise, @code{nil} (or
1049 @var{failure-value}, if provided) is returned. If @var{var} is
1050 provided, it will have either the non-@code{nil} value of @var{expr}
1051 or @var{failure-value} when the epilogue code is run.
1052
1053 As a special case, if the @var{test} expression is a sharp-quoted
1054 function, then it is applied to @var{expr} instead of being simply
1055 evaluated. E.g.@: @code{(finding x such-that #'evenp)} is equivalent to
1056 @code{(finding x such-that (evenp x))}.
1057
1058 @c \cpar although @var{test} need have nothing to do with ~@c expr~ as in
1059 @c |(finding j such-that (> i 3))|, it usually
1060 @c will: |(finding (length el) such-that (oddp (length el)))|. to
1061 @c avoid performing the |length| computation twice, you could write
1062 @c |(finding (length el) such-that \#'oddp)| or |(finding (length
1063 @c el) such-that 'oddp)|; for these cases, @iter{} generates code that
1064 @c executes @var{expr} only once. the code for |\#'oddp|
1065 @c is slightly different from that for {\lisp 'oddp}; see the discussion
1066 @c under {\lisp for\dots in} and {\lisp for\dots on}.
1067
1068 @code{On-failure} is a misnomer. Because it is always evaluated, it
1069 behaves more like the default third argument to the @code{gethash}
1070 function. As a result, @code{on-failure (error "Not found")} makes no
1071 sense. Instead, the clauses @code{leave} or @code{thereis} can be used
1072 in conjunction with @code{finally} as follows:
1073
1074 @lisp
1075 (iter (for x in '(1 2 3))
1076 (if (evenp x) (leave x))
1077 (finally (error "not found")))
1078 @end lisp
1079
1080 This clause may appear multiple times when all defaults are
1081 identical. It can also be used together with either
1082 @code{always}/@code{never} or @code{thereis} if their defaults
1083 match. More specifically, @code{on-failure nil} is compatible with
1084 @code{thereis}, while @code{on-failure t} is compatible with
1085 @code{always} and @code{never} clauses.
1086
1087 @lisp
1088 (iter (for i in '(7 -4 2 -3))
1089 (if (plusp i)
1090 (finding i such-that (evenp i))
1091 (finding (- i) such-that (oddp i))))
1092 @end lisp
1093 @end deffn
1094
1095 @claused{finding, maximizing}
1096 @claused{finding, minimizing}
1097 @deffn Clause finding @v{expr} @cl{maximizing} @v{m-expr} @
1098 @k{&optional} @k{into} @v{var}
1099 @deffnx Clause finding @v{expr} @cl{minimizing} @v{m-expr} @
1100 @k{&optional} @k{into} @v{var}
1101
1102 Computes the extremum (maximum or minimum) value of @var{m-expr} over
1103 all iterations, and returns the value of @var{expr} corresponding to
1104 the extremum. @var{expr} is evaluated inside the loop at the time the
1105 new extremum is established. If @var{m-expr} is never evaluated (due
1106 to, for example, being embedded in a conditional clause), then the
1107 returned value depends on the type, if any, of @var{expr} (or
1108 @var{var}, if one is supplied). If there is no type, the returned
1109 value will be @code{nil}; if the type is numeric, the returned value
1110 will be zero.
1111
1112 For these two clauses, @var{var} may be a list of two symbols; in that
1113 case, the first is used to record @var{expr} and the second,
1114 @var{m-expr}.
1115
1116 As with @code{finding@dots{} such-that}, if @var{m-expr} is a
1117 sharp-quoted function, then it is called on @var{expr} instead of
1118 being evaluated.
1119 @end deffn
1120
1121 @c ===================================================================
1122 @node Aggregated Boolean Tests
1123 @subsection Aggregated Boolean Tests
1124
1125 @clauseu{always}
1126 @deffn Clause always @v{expr}
1127
1128 If @var{expr} ever evaluates to @code{nil}, then @code{nil} is
1129 immediately returned; the epilogue code is not executed. If
1130 @var{expr} never evaluates to @code{nil}, the epilogue code is
1131 executed and the last value of @var{expr} (or @code{t} if @var{expr}
1132 was never evaluated) is returned (whereas @code{loop} would constantly
1133 return @code{t}).
1134
1135 @c mention last evaluated clause when multiple always clauses?
1136 @end deffn
1137
1138 @clauseu{never}
1139 @deffn Clause never @v{expr}
1140
1141 Like @code{(always (not @var{expr}))}, except it does not influence
1142 the last value returned by a possible other @code{always} clause. That
1143 is,
1144
1145 @lisp
1146 (iter (repeat 2)
1147 (always 2)
1148 (never nil)) @result{} 2 ; not t
1149 @end lisp
1150 @end deffn
1151
1152 @clauseu{thereis}
1153 @deffn Clause thereis @v{expr}
1154
1155 If @var{expr} is ever non-@code{nil}, its value is immediately
1156 returned without running epilogue code. Otherwise, the epilogue code
1157 is performed and @code{nil} is returned.
1158
1159 This clause cannot be used together with @code{always} or
1160 @code{never}, because their defaults are opposed (similarly,
1161 @code{(loop always 3 thereis nil)} refuses to compile in some
1162 implementations of @code{loop}).
1163 @end deffn
1164
1165 @c ===================================================================
1166 @node Control Flow
1167 @section Control Flow
1168
1169 Several clauses can be used to alter the usual flow of control in a
1170 loop.
1171
1172 @quotation Note
1173 The clauses of this and subsequent sections don't adhere to
1174 @iter{}'s usual syntax, but instead use standard Common Lisp syntax.
1175 Hence the format for describing syntax subsequently is like the
1176 standard format used in the Common Lisp manual, not like the
1177 descriptions of clauses above.
1178 @end quotation
1179
1180 @clauseu{finish}
1181 @deffn Clause finish
1182
1183 Stops the loop and runs the epilogue code.
1184 @end deffn
1185
1186 @c for example:
1187 @c
1188 @c @lisp
1189 @c (iter (with answer = nil)
1190 @c (initially (make-a-mess))
1191 @c (for i from 1 to 10)
1192 @c (when (correct? i)
1193 @c (setq answer i)
1194 @c (finish))
1195 @c (finally (cleanup)))
1196 @c @end lisp
1197 @c
1198 @c this code will execute |cleanup| whether or not the test |(correct?
1199 @c i)| ever succeeds.
1200 @c the (more elegant) formulation,
1201 @c @lisp
1202 @c (iter (initially (make-a-mess))
1203 @c (for i from 1 to 10)
1204 @c (finding i such-that (correct? i))
1205 @c (finally (cleanup)))
1206 @c @end lisp
1207 @c would not execute |cleanup| if |(correct? i)| succeeded; it
1208 @c would do an immediate return.
1209
1210 @clauseu{leave}
1211 @deffn Clause leave @k{&optional} @v{value}
1212
1213 Immediately returns @var{value} (default @code{nil}) from the current
1214 @iter{} form, skipping the epilogue code. Equivalent to using
1215 @code{return-from}.
1216 @end deffn
1217
1218 @clauseu{next-iteration}
1219 @deffn Clause next-iteration
1220
1221 Skips the remainder of the loop body and begins the next iteration of
1222 the loop.
1223 @end deffn
1224
1225 @clauseu{while}
1226 @deffn Clause while @v{expr}
1227
1228 If @var{expr} ever evaluates to @code{nil}, the loop is terminated and
1229 the epilogue code executed. Equivalent to @code{(if (not @var{expr})
1230 (finish))}.
1231 @end deffn
1232
1233 @clauseu{until}
1234 @deffn Clause until @v{expr}
1235
1236 Equivalent to @code{(if @var{expr} (finish))}.
1237 @end deffn
1238
1239 @clauseu{if-first-time}
1240 @deffn Clause if-first-time @v{then} @k{&optional} @v{else}
1241
1242 If this clause is being executed for the first time in this invocation
1243 of the @iter{} form, then the @var{then} code is evaluated; otherwise
1244 the @var{else} code is evaluated.
1245
1246 @code{(for @var{var} first @var{expr1} then @var{expr2})} is almost
1247 equivalent to
1248
1249 @lisp
1250 (if-first-time (dsetq @var{var} @var{expr1})
1251 (dsetq @var{var} @var{expr2}))
1252 @end lisp
1253
1254 The only difference is that the @code{for} version makes @var{var}
1255 available for use with @code{for@dots{} previous}.
1256 @end deffn
1257
1258 @c ===================================================================
1259 @node Predicates
1260 @section Predicates
1261
1262 @quotation Compatibility Note
1263 The clauses in this section were added in the twenty-first century and
1264 not part of Jonathan Amsterdam's original design.
1265 @end quotation
1266
1267 @clauseu{first-iteration-p}
1268 @deffn Clause first-iteration-p
1269
1270 Returns @code{t} in the first iteration of the loop, otherwise @code{nil}.
1271 @end deffn
1272
1273 @clauseu{first-time-p}
1274 @deffn Clause first-time-p
1275
1276 Returns @code{t} the first time the expression is evaluated, and then
1277 @code{nil} forever. This clause comes handy when printing (optional)
1278 elements separated by a comma:
1279
1280 @lisp
1281 (iter (for el in '(nil 1 2 nil 3))
1282 (when el
1283 (unless (first-time-p)
1284 (princ ", "))
1285 (princ el)))
1286 @print{} 1, 2, 3
1287 @end lisp
1288 @end deffn
1289
1290 @c ===================================================================
1291 @node Code Placement
1292 @section Code Placement
1293
1294 When fine control is desired over where code appears in a loop
1295 generated by @iter{}, the following special clauses may be useful.
1296 They are all subject to code-motion problems (see @ref{Problems with
1297 Code Movement}).
1298
1299 @clauseu{initially}
1300 @deffn Clause initially @k{&rest} @var{forms}
1301
1302 The lisp @var{forms} are placed in the prologue section of the loop,
1303 where they are executed once, before the loop body is entered.
1304 @end deffn
1305
1306 @clauseu{after-each}
1307 @deffn Clause after-each @k{&rest} @v{forms}
1308
1309 The @var{forms} are placed at the end of the loop body, where they
1310 are executed after each iteration. Unlike the other clauses in this
1311 section, @var{forms} may contain @iter{} clauses.
1312 @end deffn
1313
1314 @clauseu{else}
1315 @deffn Clause else @k{&rest} @v{forms}
1316
1317 The lisp @var{forms} are placed in the epilogue section of the loop,
1318 where they are executed if this @code{else} clause is never met during
1319 execution of the loop and the loop terminates normally.
1320 @end deffn
1321
1322 @clauseu{finally}
1323 @deffn Clause finally @k{&rest} @v{forms}
1324
1325 The lisp @var{forms} are placed in the epilogue section of the loop,
1326 where they are executed after the loop has terminated normally.
1327 @end deffn
1328
1329 @clauseu{finally-protected}
1330 @deffn finally-protected @k{&rest} @v{forms}
1331
1332 The lisp @var{forms} are placed in the second form of an
1333 @code{unwind-protect} outside the loop. They are always executed
1334 after the loop has terminated, regardless of how the termination
1335 occurred.
1336 @end deffn
1337
1338 @c ===================================================================
1339 @node Other Features
1340 @chapter Other Features
1341
1342 @section Multiple Accumulations
1343
1344 It is permitted to have more than one clause accumulate into the same
1345 variable, as in the following:
1346
1347 @lisp
1348 (iter (for i from 1 to 10)
1349 (collect i into nums)
1350 (collect (sqrt i) into nums)
1351 (finally (return nums)))
1352 @end lisp
1353
1354 Clauses can only accumulate into the same variable if they are
1355 compatible. @code{collect}, @code{adjoining}, @code{appending},
1356 @code{nconcing}, @code{unioning} and @code{nunioning} are compatible
1357 with each other; @code{sum}, @code{multiply} and @code{counting} are
1358 compatible; @code{always} and @code{never} are compatible;
1359 @code{finding}@dots{} @code{such-that} is compatible with either
1360 @code{thereis} or @code{always} and @code{never} when their defaults
1361 match; and @code{maximize} and @code{minimize} clauses are compatible
1362 only with other @code{maximize} and @code{minimize} clauses,
1363 respectively.
1364
1365 @c note that the same variable ~cannot~ be both an accumulation
1366 @c variable and an ordinary variable; there can be only one variable
1367 @c with a given name within an @iter{} form.
1368
1369 @menu
1370 * Named Blocks::
1371 * Destructuring::
1372 * On-line Help::
1373 * Parallel Binding and Stepping::
1374 @end menu
1375
1376 @c ===================================================================
1377 @node Named Blocks
1378 @section Named Blocks
1379
1380 Like Common Lisp @code{block}s, @iter{} forms can be given names. The
1381 name should be a single symbol, and it must be the first form in the
1382 @iter{}. The generated code behaves exactly like a named block; in
1383 particular, @code{(return-from @var{name})} can be used to exit it:
1384
1385 @lisp
1386 (iter fred
1387 (for i from 1 to 10)
1388 (iter barney
1389 (for j from i to 10)
1390 (if (> (* i j) 17)
1391 (return-from fred j))))
1392 @end lisp
1393
1394 An @iter{} form that is not given a name is implicitly named
1395 @code{nil}.
1396
1397 Sometimes one would like to write an expression in an inner @iter{}
1398 form, but have it processed by an outer @iter{} form. This is
1399 possible with the @code{in} clause.
1400
1401 @clauseu{in}
1402 @deffn Clause in @v{name} @k{&rest} @v{forms}
1403
1404 Evaluates @var{forms} as if they were part of the @iter{} form named
1405 @var{name}. In other words, @iter{} clauses are processed by the
1406 @iter{} form named @var{name}, and not by any @iter{} forms that occur
1407 inside @var{name}.
1408
1409 As an example, consider the problem of collecting a list of the
1410 elements in a two-dimensional array. The naive solution,
1411 @lisp
1412 (iter (for i below (array-dimension ar 0))
1413 (iter (for j below (array-dimension ar 1))
1414 (collect (aref ar i j))))
1415 @end lisp
1416 is wrong because the list created by the inner @iter{} is simply
1417 ignored by the outer one. But using @code{in} we can write:
1418 @lisp
1419 (iter outer (for i below (array-dimension ar 0))
1420 (iter (for j below (array-dimension ar 1))
1421 (in outer (collect (aref ar i j)))))
1422 @end lisp
1423 which has the desired result.
1424 @end deffn
1425
1426 @c ===================================================================
1427 @node Destructuring
1428 @section Destructuring
1429
1430 In many places within @iter{} clauses where a variable is expected, a
1431 list can be written instead. In these cases, the value to be assigned
1432 is @emph{destructured} according to the pattern described by the list.
1433 As a simple example, the clause
1434 @lisp
1435 (for (key . item) in alist)
1436 @end lisp
1437 will result in @code{key} being set to the @code{car} of each element
1438 in @code{alist}, and @code{item} being set to the @code{cdr}. The
1439 pattern list may be nested to arbitrary depth, and (as the example
1440 shows) need not be terminated with @code{nil}; the only requirement is
1441 that each leaf be a bindable symbol (or @code{nil}, in which case no
1442 binding is generated for that piece of the structure).
1443
1444 Sometimes, you might like to do the equivalent of a
1445 @code{multiple-value-setq} in a clause. This ``multiple-value
1446 destructuring'' can be expressed by writing @code{(values @var{pat_1}
1447 @var{pat_2} @dots{})} for a destructuring pattern, as in
1448
1449 @lisp
1450 (for (values (a . b) c d) = (three-valued-function ...))
1451 @end lisp
1452
1453 Note that the @var{pat_i} can themselves be destructuring patterns
1454 (though not multiple-value destructuring patterns). You can't do
1455 multiple-value destructuring in a @code{with} clause; instead wrap the
1456 whole @iter{} form in a @code{multiple-value-bind}.
1457
1458 @quotation Rationale
1459 There are subtle interactions between variable declarations and
1460 evaluation order that make the correct implementation of
1461 multiple-value destructuring in a @code{with} somewhat tricky.
1462 @end quotation
1463
1464 The destructuring feature of @iter{} is available as a separate
1465 mechanism, using the @code{dsetq} macro:
1466
1467 @itindex dsetq
1468 @defmac dsetq @v{template} @v{expr}
1469
1470 Performs destructuring of @var{expr} using @var{template}. May be
1471 used outside of an @iter{} form. Yields the primary value of
1472 @var{expr}.
1473 @end defmac
1474
1475 @c ===================================================================
1476 @node On-line Help
1477 @section On-line Help
1478
1479 There is a limited facility for on-line help, in the form of the
1480 @code{display-iterate-clauses} function.
1481
1482 @itindex display-iterate-clauses
1483 @defun display-iterate-clauses @k{&optional} @v{clause-spec}
1484
1485 Displays a list of @iter{} clauses. If @var{clause-spec} is not
1486 provided, all clauses are shown; if it is a symbol, all clauses
1487 beginning with that symbol are shown; and if it is a list of symbols,
1488 all clauses for which @var{clause-spec} is a prefix are shown.
1489 @end defun
1490
1491 @c ===================================================================
1492 @node Parallel Binding and Stepping
1493 @section Parallel Binding and Stepping
1494
1495 The parallel binding and stepping of variables is a feature that
1496 @iter{} does @emph{not} have. This section attempts to provide a
1497 rationale.
1498
1499 We say that two variables are bound @emph{in parallel} if neither
1500 binding shadows the other. This is the usual semantics of @code{let}
1501 (as opposed to @code{let*}). Similarly, we can say that iteration
1502 variables are stepped in parallel if neither variable is updated
1503 before the other, conceptually speaking; in other words, if the code
1504 to update each variable can reference the old values of both
1505 variables.
1506
1507 @code{loop} allows parallel binding of variables and parallel stepping
1508 of driver variables. My view is that if you are depending on the
1509 serial/parallel distinction, you are doing something obscure. If you
1510 need to bind variables in parallel using @code{with}, then you must be
1511 using a variable name that shadows a name in the existing lexical
1512 environment. Don't do that. The most common use for parallel
1513 stepping is to track the values of variables on the previous
1514 iteration, but in fact this does not require parallel stepping at all;
1515 the following will work:
1516
1517 @lisp
1518 (iter (for current in list)
1519 (for prev previous current)
1520 @dots{})
1521 @end lisp
1522
1523 @c ===================================================================
1524 @node Types and Declarations
1525 @chapter Types and Declarations
1526
1527 @section Discussion
1528
1529 Sometimes efficiency dictates that the types of variables be declared.
1530 This type information needs to be communicated to @iter{} so it can
1531 bind variables to appropriate values. Furthermore, @iter{} must often
1532 generate internal variables invisible to the user; there needs to be a
1533 way for these to be declared.
1534
1535 As an example, consider this code, which will return the number of
1536 odd elements in @code{number-list}:
1537
1538 @lisp
1539 (iter (for el in number-list)
1540 (count (oddp el)))
1541 @end lisp
1542
1543 In processing this form, @iter{} will create an internal variable, let
1544 us call it @code{list17}, to hold the successive @code{cdr}s of
1545 @code{number-list}, and will bind the variable to @code{number-list}.
1546 It will also generate a default binding for @code{el}; only inside the
1547 body of the loop will @code{el} be set to the @code{car} of
1548 @code{list17}. Finally, @iter{} will generate a variable, call it
1549 @code{result}, to hold the result of the count, and will bind it to
1550 zero.
1551
1552 When dealing with type declarations, @iter{} observes one simple rule:
1553 @emph{it will never generate a declaration unless requested to do so}.
1554 The reason is that such declarations might mask errors in compiled
1555 code by avoiding error-checks; the resulting problems would be doubly
1556 hard to track down because the declarations would be hidden from the
1557 programmer. Of course, a compiler might omit error-checks even in the
1558 absence of declarations, though this behavior can usually be avoided,
1559 e.g.@: by saying @code{(declaim (optimize (safety 3)))}.
1560
1561 So, the above @iter{} form will generate code with no declarations.
1562 But say we wish to declare the types of @code{el} and the internal
1563 variables @code{list17} and @code{result}. How is this done?
1564
1565 Declaring the type of @code{el} is easy, since the programmer knows
1566 the variable's name:
1567
1568 @lisp
1569 (iter (for el in number-list)
1570 (declare (fixnum el))
1571 (counting (oddp el)))
1572 @end lisp
1573
1574 @iter{} can read variable type declarations like this one. Before
1575 processing any clauses, it scans the entire top-level form for type
1576 declarations and records the types, so that variable bindings can be
1577 performed correctly. In this case, @code{el} will be bound to zero
1578 instead of @code{nil}. Also, @iter{} collects all the top-level
1579 declarations and puts them at the begining of the generated code, so
1580 it is not necessary to place all declarations at the beginning of an
1581 @iter{} form; instead, they can be written near the variables whose
1582 types they declare.
1583
1584 Since @iter{} is not part of the compiler, it will not know
1585 about declarations that occur outside an @iter{} form; these
1586 declarations must be repeated inside the form.
1587
1588 Here is another way we could have declared the type of @code{el}:
1589
1590 @lisp
1591 (iter (for (the fixnum el) in number-list)
1592 (counting (oddp el)))
1593 @end lisp
1594
1595 @itindex the
1596 @iter{} extends the Common Lisp @code{the} form to apply to variables
1597 as well as value-producing forms; anywhere a variable is allowed---in
1598 a @code{with} clause, as the iteration variable in a driver clause, as
1599 the @code{into} argument of an accumulation clause, even inside a
1600 destructuring template---you can write @code{(the @var{type}
1601 @var{symbol})} instead.
1602
1603 There is one crucial difference between using a @code{the} form and
1604 actually declaring the variable: explicit declarations are always
1605 placed in the generated code, but type information from a @code{the}
1606 form is not turned into an actual declaration unless you tell @iter{}
1607 to do so using @code{iterate:declare-variables}. See below.
1608
1609 Declaring the types of internal variables is harder than declaring the
1610 types of explicitly mentioned variables, since their names are
1611 unknown. You do it by declaring @code{iterate:declare-variables}
1612 somewhere inside the top level of the @iter{} form. (This will also
1613 generate declarations for variables declared using @code{the}.)
1614 @iter{} does not provide much selectivity here: it's all or none. And
1615 unfortunately, since @iter{} is not privy to compiler information but
1616 instead reads declarations itself, it will not hear if you
1617 @code{(declaim (iterate:declare-variables))}. Instead, set the
1618 variable @code{iterate::*always-declare-variables*} to @code{t} at
1619 compile-time, using @code{eval-when}.
1620
1621 To determine the appropriate types for internal variables, @iter{}
1622 uses three sources of information:
1623
1624 @itemize
1625 @item
1626 Often, the particular clause dictates a certain type for a
1627 variable; @iter{} will use this information when available. In the
1628 current example, the variable @code{list17} will be given the type
1629 @code{list}, since that is the only type that makes sense; and the
1630 variable @code{result} will be given the type @code{fixnum}, on the
1631 assumption that you will not be counting high enough to need bignums.
1632 You can override this assumption on @code{count}, @code{sum} and
1633 @code{multiply} clauses (and their synonyms, @code{counting},
1634 @code{summing} and @code{multiplying}) using the optional
1635 @code{result-type} argument:
1636
1637 @lisp
1638 (iter (declare (iterate:declare-variables))
1639 (for el in number-list)
1640 (count (oddp el) result-type integer))
1641 @end lisp
1642
1643 Alterately, you can override it on any form which takes an optional
1644 @code{into var} argument by declaring the type of @code{var} and
1645 explicitly returning it:
1646
1647 @lisp
1648 (iter (declare (iterate:declare-variables))
1649 (for el in number-list)
1650 (count (oddp el) into my-result)
1651 (declare (integer my-result))
1652 (finally (return my-result)))
1653 @end lisp
1654
1655 Other examples of the type assumptions that @iter{} makes are: type
1656 @code{list} for @code{into} variables of collection clauses; type
1657 @code{list} for expressions that are to be destructured; type
1658 @code{vector} for the variable holding the vector in a
1659 @code{for@dots{} in-vector} clause, and similarly for @code{string}
1660 and the @code{for@dots{} in-string} clause; and the
1661 implementation-dependent type @code{(type-of array-dimension-limit)}
1662 for the index and limit variables generated by sequence iteration
1663 drivers like @code{for@dots{} in-vector} and @code{for@dots{}
1664 in-string} (but not @code{for@dots{} in-sequence}, because it may be
1665 used to iterate over a list).
1666
1667 @item
1668 Sometimes, @iter{} will examine expressions and try to determine their
1669 types in a simple-minded way. If the expression is self-evaluating
1670 (like a number, for instance), @iter{} knows that the expression's
1671 type is the same as the type of the value it denotes, so it can use
1672 that type. If the expression is of the form @code{(the @var{type}
1673 @var{expr})}, @iter{} is smart enough to extract @var{type} and use
1674 it. However, the current version of @iter{} does not examine
1675 declarations of function result types or do any type inference. It
1676 will not determine, for example, that the type of @code{(+ 3 4)} is
1677 @code{fixnum}, or even @code{number}.
1678
1679 @item
1680 In some cases, the type of an internal variable should match the type
1681 of some other variable. For instance, @iter{} generates an internal
1682 variable for @code{(f x)} in the clause @code{(for i from 1 to (f
1683 x))}, and in the absence of other information will give it the same
1684 type as @code{i}. If, however, the expression had been written
1685 @code{(the fixnum (f x))}, then @iter{} would have given the internal
1686 variable the type @code{fixnum} regardless of @code{i}'s type. The
1687 type incompatibility errors that could arise in this situation are not
1688 checked for.
1689 @end itemize
1690
1691 Note that if you do declare @code{iterate:declare-variables}, then
1692 @iter{} may declare user variables as well as internal ones if they do
1693 not already have declarations, though only for variables that it
1694 binds. For instance, in this code:
1695
1696 @lisp
1697 (iter (declare (iterate:declare-variables))
1698 (for i from 1 to 10)
1699 (collect i into var))
1700 @end lisp
1701
1702 the variable @code{var} will be declared to be of type @code{list}.
1703
1704 @section Summary
1705
1706 @itindex declare-variables
1707 @itindex *always-declare-variables*
1708 @iter{} understands standard Common Lisp variable type declarations
1709 that occur within an @iter{} form and will pass them through to the
1710 generated code. If the declaration @code{(iterate:declare-variables)}
1711 appears at the top level of an @iter{} form, or if
1712 @code{iterate::*always-declare-variables*} is non-@code{nil}, then
1713 @iter{} will use the type information gleaned from user declarations,
1714 self-evaluating expressions and @code{the} expressions, combined with
1715 reasonable assumptions, to determine variable types and declare them.
1716
1717 @c ===================================================================
1718 @node Problems with Code Movement
1719 @chapter Problems with Code Movement
1720
1721 Some @iter{} clauses, or parts of clauses, result in code being moved
1722 from the location of the clause to other parts of the loop. Drivers
1723 behave this way, as do code-placement clauses like @code{initially}
1724 and @code{finally}. When using these clauses, there is a danger of
1725 writing an expression that makes sense in its apparent location but
1726 will be invalid or have a different meaning in another location. For
1727 example:
1728
1729 @lisp
1730 (iter (for i from 1 to 10)
1731 (let ((x 3))
1732 (initially (setq x 4))))
1733 @end lisp
1734
1735 While it may appear that the @code{x} of @code{(initially (setq x 4))}
1736 is the same as the @code{x} of @code{(let ((x 3)) @dots{}}, in fact
1737 they are not: @code{initially} moves its code outside the loop body,
1738 so @code{x} would refer to a global variable. Here is another example
1739 of the same problem:
1740
1741 @lisp
1742 (iter (for i from 1 to 10)
1743 (let ((x 3))
1744 (collect i into x)))
1745 @end lisp
1746
1747 If this code were executed, @code{collect} would create a binding for
1748 its @code{x} at the top level of the @iter{} form that the @code{let}
1749 will shadow.
1750
1751 Happily, @iter{} is smart enough to catch these errors; it walks all
1752 problematical code to ensure that free variables are not bound inside
1753 the loop body, and checks all variables it binds for the same problem.
1754
1755 However, some errors cannot be caught:
1756
1757 @lisp
1758 (iter (with x = 3)
1759 (for el in list)
1760 (setq x 1)
1761 (reducing el by #'+ initial-value x))
1762 @end lisp
1763
1764 @code{reducing} moves its @code{initial-value} argument to the
1765 initialization part of the loop in order to produce more efficient
1766 code. Since @iter{} does not perform data-flow analysis, it cannot
1767 determine that @code{x} is changed inside the loop; all it can
1768 establish is that @code{x} is not bound internally. Hence this code
1769 will not signal an error and will use @math{3} as the initial value of
1770 the reduction.
1771
1772 The following list summarizes all cases that are subject to these code
1773 motion and variable-shadowing problems.
1774
1775 @itemize
1776 @item
1777 Any variable for which @iter{} creates a binding, including those used
1778 in @code{with} and the @code{into} keyword of many clauses.
1779
1780 @item
1781 The special clauses which place code: @code{initially},
1782 @code{after-each}, @code{else}, @code{finally} and
1783 @code{finally-protected}.
1784
1785 @item
1786 The variables of a @code{next} or @code{do-next} form.
1787
1788 @item
1789 The @code{initially} arguments of @code{for@dots{} initially@dots{}
1790 then} and @code{for@dots{} previous}.
1791
1792 @item
1793 The @code{then} argument of @code{for@dots{} initially@dots{} then}.
1794
1795 @item
1796 The @code{initial-value} arguments of @code{reducing} and
1797 @code{accumulate}.
1798
1799 @item
1800 The @code{on-failure} argument of @code{finding@dots{} such-that}.
1801 @end itemize
1802
1803 @c ===================================================================
1804 @node Differences Between Iterate and Loop
1805 @chapter Differences Between @code{Iterate} and @code{Loop}
1806
1807 @code{loop} contains a great deal of complexity which @iter{} tries to
1808 avoid. Hence many esoteric features of @code{loop} don't exist in
1809 @iter{}. Other features have been carried over, but in a cleaned-up
1810 form. And of course, many new features have been added; they are not
1811 mentioned in this list.
1812
1813 @itemize
1814 @item
1815 @iter{}'s syntax is more Lisp-like than @code{loop}'s, having a higher
1816 density of parens.
1817
1818 @item
1819 The current implementation of @iter{}, unlike the standardised version
1820 of @code{loop}, is extensible (see @ref{Rolling Your Own}).
1821
1822 @item
1823 @code{loop} puts the updates of all driver variables at the top of the
1824 loop; @iter{} leaves them where the driver clauses appear. In
1825 particular, @iter{} allows to place drivers after @code{while} clauses.
1826
1827 @item
1828 While for the most part @iter{} clauses that resemble @code{loop}
1829 clauses behave similarly, there are some differences. For instance,
1830 there is no @code{for@dots{} =@dots{} then} in @iter{}; instead use
1831 @code{for@dots{} initially@dots{} then}.
1832
1833 @item
1834 @code{loop} binds the variable @code{it} at certain times to allow
1835 pseudo-English expressions like @code{when @var{expr} return it}. In
1836 @iter{}, you must bind @var{expr} to a variable yourself. Note that
1837 @code{when @var{expr} return it} is like @code{thereis @var{expr}}
1838 except that the latter is an accumulation clause and therefore
1839 competes with other accumulations (remember ``Multiple Accumulations''
1840 in @ref{Other Features}).
1841
1842 @c repeat different behaviour of |always| clause here?
1843
1844 @item
1845 @code{loop} has a special @code{return} clause, illustrated in the
1846 previous item. @iter{} doesn't need one, since an ordinary Lisp
1847 @code{return} has the same effect.
1848
1849 @item
1850 @code{loop} allows for parallel binding and stepping of iteration
1851 variables. @iter{} does not. (See @ref{Parallel Binding and
1852 Stepping}.)
1853
1854 @item
1855 @code{loop} and @iter{} handle variable type declarations very
1856 differently. @code{loop} provides a special syntax for declaring
1857 variable types, and does not examine declarations. Moreover, the
1858 standard implementation of @code{loop} will generate declarations when
1859 none are requested. @iter{} parses standard Common Lisp type
1860 declarations, and will never declare a variable itself unless
1861 declarations are specifically requested.
1862 @end itemize
1863
1864 @c ===================================================================
1865 @node Rolling Your Own
1866 @chapter Rolling Your Own
1867
1868 @section Introduction
1869
1870 @iter{} is extensible---you can write new clauses that embody new
1871 iteration patterns. You might want to write a new driver clause for a
1872 data structure of your own, or you might want to write a clause that
1873 collects or manipulates elements in a way not provided by @iter{}.
1874
1875 This section describes how to write clauses for @iter{}. Writing a
1876 clause is like writing a macro. In fact, writing a clause @emph{is}
1877 writing a macro: since @iter{} code-walks its body and macroexpands,
1878 you can add new abstractions to @iter{} with good old @code{defmacro}.
1879
1880 Actually, there are two extensions you can make to @iter{} that are
1881 even easier than writing a macro. They are adding a synonym for an
1882 existing clause and defining a driver clause for an indexable
1883 sequence. These can be done with @code{defsynonym} and
1884 @code{defclause-sequence}, respectively. See @ref{Extensibility
1885 Aids}.
1886
1887 The rest of this section explains how to write macros that expand into
1888 @iter{} clauses. Here's how you could add a simplified version of
1889 @iter{}'s @code{multiply} clause, if @iter{} didn't already have one:
1890
1891 @lisp
1892 (defmacro multiply (expr)
1893 `(reducing ,expr by #'* initial-value 1))
1894 @end lisp
1895
1896 If you found yourself summing the square of an expression often, you
1897 might want to write a macro for that. A first cut might be
1898
1899 @lisp
1900 (defmacro sum-of-squares (expr)
1901 `(sum (* ,expr ,expr)))
1902 @end lisp
1903
1904 but if you are an experienced macro writer, you will realize that this
1905 code will evaluate @var{expr} twice, which is probably a bad idea. A
1906 better version would use a temporary:
1907
1908 @lisp
1909 (defmacro sum-of-squares (expr)
1910 (let ((temp (gensym)))
1911 `(let ((,temp ,expr))
1912 (sum (* ,temp ,temp)))))
1913 @end lisp
1914
1915 Although this may seem complex, it is just the sort of thing you'd
1916 have to go through to write any macro, which illustrates the point of
1917 this section: if you can write macros, you can extend @iter{}.
1918
1919 Our macros don't use @iter{}'s keyword-argument syntax. We could just
1920 use keywords with @code{defmacro}, but we would still not be using
1921 @iter{}'s clause indexing mechanism. Unlike Lisp, which uses just the
1922 first symbol of a form to determine what function to call, @iter{}
1923 individuates clauses by the list of required keywords. For instance,
1924 @code{for@dots{} in} and @code{for@dots{} in-vector} are different
1925 clauses implemented by distinct Lisp functions.
1926
1927 To buy into this indexing scheme, as well as the keyword-argument
1928 syntax, use @code{defmacro-clause}:
1929
1930 @itindex defmacro-clause
1931 @defmac defmacro-clause @v{arglist} @k{&body} @v{body}
1932
1933 Defines a new @iter{} clause. @var{arglist} is a list of symbols
1934 which are alternating keywords and arguments. @code{&optional} may be
1935 used, and the list may be terminated by @code{&sequence}. @var{body}
1936 is an ordinary macro body, as with @code{defmacro}. If the first form
1937 of @var{body} is a string, it is considered a documentation string and
1938 will be shown by
1939 @code{display-iterate-clauses}. @code{defmacro-clause} will signal an
1940 error if defining the clause would result in an ambiguity. E.g.@: you
1941 cannot define the clause @code{for@dots{} from} because there would be
1942 no way to distinguish it from a use of the @code{for} clause with
1943 optional keyword @code{from}.
1944 @end defmac
1945
1946 Here is @code{multiply} using @code{defmacro-clause}. The keywords
1947 are capitalized for readability.
1948
1949 @lisp
1950 (defmacro-clause (MULTIPLY expr &optional INTO var)
1951 `(reducing ,expr by #'* into ,var initial-value 1))
1952 @end lisp
1953
1954 You don't have to worry about the case when @code{var} is not
1955 supplied; for any clause with an @code{into} keyword, saying
1956 @code{into nil} is equivalent to omitting the @code{into} entirely.
1957
1958 As another, more extended example, consider the fairly common
1959 iteration pattern that involves finding the sequence element that
1960 maximizes (or minimizes) some function. @iter{} provides this as
1961 @code{finding@dots{} maximizing}, but it's instructive to see how to
1962 write it. Here, in pseudocode, is how you might write such a loop for
1963 maximizing a function F:
1964
1965 @example
1966 @r{set variable MAX-VAL to NIL;}
1967 @r{set variable WINNER to NIL;}
1968 @r{for each element EL in the sequence}
1969 @r{if MAX-VAL is NIL or F(EL) > MAX-VAL then}
1970 @r{set MAX-VAL to F(EL);}
1971 @r{set WINNER to EL;}
1972 @r{end if;}
1973 @r{end for;}
1974 @r{return WINNER.}
1975 @end example
1976
1977 Here is the macro:
1978
1979 @lisp
1980 (defmacro-clause (FINDING expr MAXIMIZING func &optional INTO var)
1981 "Simple FINDING... MAXIMIZING implementation"
1982 (let ((max-val (gensym "MAX-VAL"))
1983 (temp1 (gensym "EL"))
1984 (temp2 (gensym "VAL"))
1985 (winner (or var iterate::*result-var*)))
1986 `(progn
1987 (with ,max-val = nil)
1988 (with ,winner = nil)
1989 (let* ((,temp1 ,expr)
1990 (,temp2 (funcall ,func ,temp1)))
1991 (when (or (null ,max-val) (> ,temp2 ,max-val))
1992 (setq ,winner ,temp1 ,max-val ,temp2))))))
1993 @end lisp
1994
1995 @c This example differs from the built-in finder:
1996 @c - The built-in one specifies the clause's value (el so far)
1997 @c (trivial to implement: add ,winner at end of progn)
1998 @c - The built-in one accepts an (el max-val) tuple var spec.
1999 @c - Influence of (the type var) on type declarations
2000
2001 Note that if no @code{into} variable is supplied, we use
2002 @code{iterate::*result-var*}, which contains the internal variable
2003 into which all clauses place their results. If this variable is bound
2004 by some clause, then @iter{} will return its value automatically;
2005 otherwise, @code{nil} will be returned.
2006
2007 @c The original example had four flaws:
2008 @c - ,expr and ,func occured twice in expansion
2009 @c - (finally (leave ,winner)) breaks because FINALLY does not walk
2010 @c its forms, so LEAVE does not work inside FINALLY.
2011 @c - Do not use (finally (return ,winner)) either, as that would
2012 @c always return winner, even in case of ... INTO nil.
2013 @c - Value of clause as form undefined, unlike all built-in clauses
2014
2015 @menu
2016 * Writing Drivers::
2017 * Extensibility Aids::
2018 * Subtleties::
2019 @end menu
2020
2021 @c ===================================================================
2022 @node Writing Drivers
2023 @section Writing Drivers
2024
2025 In principle, drivers can be implemented just as easily as other
2026 @iter{} clauses. In practice, they are a little harder to get right.
2027 As an example, consider writing a driver that iterates over all the
2028 elements of a vector, ignoring its fill-pointer. @code{for@dots{}
2029 in-vector} won't work for this, because it observes the fill-pointer.
2030 It's necessary to use @code{array-dimension} instead of @code{length}
2031 to obtain the size of the vector. Here is one approach:
2032
2033 @lisp
2034 (defmacro-clause (FOR var IN-WHOLE-VECTOR v)
2035 "All the elements of a vector (disregards fill-pointer)"
2036 (let ((vect (gensym))
2037 (index (gensym)))
2038 `(progn
2039 (with ,vect = ,v)
2040 (for ,index from 0 below (array-dimension ,vect 0))
2041 (for ,var = (aref ,vect ,index)))))
2042 @end lisp
2043
2044 Note that we immediately put @code{v} in a variable, in case it is an
2045 expression. Again, this is just good Lisp macrology. It also has a
2046 subtle effect on the semantics of the driver: @code{v} is evaluated
2047 only once, at the beginning of the loop, so changes to @code{v} in the
2048 loop have no effect on the driver. Similarly, the bounds for
2049 numerical iteration e.g.@: the above @code{array-dimension} are also
2050 evaluated once only. This is how all of @iter{}'s drivers work.
2051
2052 There is an important point concerning the @code{progn} in this code.
2053 We need the @code{progn}, of course, because we are returning several
2054 forms, one of which is a driver. But @iter{} drivers must occur at
2055 top-level. Is this code in error? No, because @emph{top-level} is
2056 defined in @iter{} to include forms inside a @code{progn}. This is
2057 just the definition of top-level that Common Lisp uses, and for the
2058 same reason: to allow macros to return multiple forms at top-level.
2059
2060 While our @code{for@dots{} in-whole-vector} clause will work, it is
2061 not ideal. In particular, it does not support generating. Do do so,
2062 we need to use @code{for@dots{} next} or @code{for@dots{} do-next}.
2063 The job is simplified by the @code{defmacro-driver} macro.
2064
2065 @itindex defmacro-driver
2066 @defmac defmacro-driver @v{arglist} @k{&body} @v{body}
2067
2068 Defines a driver clause in both the @code{for} and @code{generate}
2069 forms, and provides a parameter @code{generate} which @var{body} can
2070 examine to determine how it was invoked. @var{arglist} is as in
2071 @code{defmacro-clause}, and should begin with the symbol @code{for}.
2072 @end defmac
2073
2074 With @code{defmacro-driver}, our driver looks like this:
2075
2076 @lisp
2077 (defmacro-driver (FOR var IN-WHOLE-VECTOR v)
2078 "All the elements of a vector (disregards fill-pointer)"
2079 (let ((vect (gensym))
2080 (end (gensym))
2081 (index (gensym))
2082 (kwd (if generate 'generate 'for)))
2083 `(progn
2084 (with ,vect = ,v)
2085 (with ,end = (array-dimension ,vect 0))
2086 (with ,index = -1)
2087 (,kwd ,var next (progn (incf ,index)
2088 (if (>= ,index ,end) (terminate))
2089 (aref ,vect ,index))))))
2090 @end lisp
2091
2092 We are still missing one thing: the @code{&sequence} keywords.
2093 We can get them easily enough, by writing
2094
2095 @lisp
2096 (defmacro-driver (FOR var IN-WHOLE-VECTOR v &sequence)
2097 @dots{})
2098 @end lisp
2099
2100 We can now refer to parameters @code{from}, @code{to}, @code{by},
2101 etc.@: which contain either the values for the corresponding keyword, or
2102 @code{nil} if the keyword was not supplied. Implementing the right
2103 code for these keywords is cumbersome but not difficult; it is left as
2104 an exercise. But before you begin, see @code{defclause-sequence}
2105 below for an easier way.
2106
2107 @c ===================================================================
2108 @node Extensibility Aids
2109 @section Extensibility Aids
2110
2111 This section documents assorted features that may be of use in
2112 extending @iter{}.
2113
2114 @itindex *result-var*
2115 @defvr {Unexported Variable} *result-var*
2116
2117 Holds the variable that is used to return a value as a result of the
2118 @iter{} form. You may examine this and use it in a @code{with}
2119 clause, but you should not change it.
2120 @end defvr
2121
2122 @itindex defsynonym
2123 @defmac defsynonym @v{syn} @v{word}
2124
2125 Makes @var{syn} a synonym for the existing @iter{} keyword @var{word}.
2126 Only the first word in each clause can have synonyms.
2127 @end defmac
2128
2129 @itindex defclause-sequence
2130 @defmac defclause-sequence @v{element-name} @v{index-name} @k{&key} @
2131 @v{access-fn} @v{size-fn} @v{sequence-type} @
2132 @v{element-type} @v{element-doc-string} @
2133 @v{index-doc-string}
2134
2135 Provides a simple way to define sequence clauses. Generates two
2136 clauses, one for iterating over the sequence's elements, the other for
2137 iterating over its indices. The first symbol of both clauses will
2138 have print-name @code{for}. @var{element-name} and @var{index-name}
2139 should be symbols. @var{element-name} is the second keyword of the
2140 element iterator (typically of the form
2141 @code{in-@var{sequence-type}}), and @var{index-name} is the second
2142 keyword of the index-iterator (typically of the form
2143 @code{index-of-@var{sequence-type}}). Either name may be @code{nil},
2144 in which case the corresponding clause is not defined. If both
2145 symbols are supplied, they should be in the same package. The
2146 @code{for} that begins the clauses will be in this package.
2147
2148 @var{access-fn} is the function to be used to access elements of the
2149 sequence in the element iterator. The function should take two
2150 arguments, a sequence and an index, and return the appropriate
2151 element. @var{size-fn} should denote a function of one argument, a
2152 sequence, that returns its size. Both @var{access-fn} and
2153 @var{size-fn} are required for the element iterator, but only
2154 @var{size-fn} is needed for the index iterator.
2155
2156 The @var{sequence-type} and @var{element-type} keywords are used to
2157 suggest types for the variables used to hold the sequence and the
2158 sequence elements, respectively. The usual rules about @iter{}'s
2159 treatment of variable type declarations apply (see @ref{Types and
2160 Declarations}).
2161
2162 @var{element-doc-string} and @var{index-doc-string} are the
2163 documentation strings, for use with @code{display-iterate-clauses}.
2164
2165 The generated element-iterator performs destructuring on the element
2166 variable.
2167 @end defmac
2168
2169 As an example, the above @code{for@dots{} in-whole-vector} example
2170 could have been written:
2171
2172 @lisp
2173 (defclause-sequence IN-WHOLE-VECTOR INDEX-OF-WHOLE-VECTOR
2174 :access-fn 'aref
2175 :size-fn (lambda (v) (array-dimension v 0))
2176 :sequence-type 'vector
2177 :element-type t
2178 :element-doc-string "Elements of a vector, disregarding fill-pointer"
2179 :index-doc-string "Indices of vector, disregarding fill-pointer")
2180 @end lisp
2181
2182 @c ===================================================================
2183 @node Subtleties
2184 @section Subtleties
2185
2186 There are some subtleties to be aware of when writing @iter{} clauses.
2187 First, the code returned by your macros may be @code{nconc}'ed into a
2188 list, so you should always returned freshly consed lists, rather than
2189 constants. Second, @iter{} matches clauses by using @code{eq} on the
2190 first symbol and @code{string=} on the subsequent ones, so the package
2191 of the first symbol of a clause is relevant. All of the clauses in
2192 this manual have their first word in the @iter{} package. You can use
2193 the package system in the usual way to shadow @iter{} clauses without
2194 replacing them.
2195
2196 @c say more here, about the badness that only the first word of a
2197 @c clause is packagey.
2198
2199 @c ===================================================================
2200 @node Non-portable Extensions to Iterate (Contribs)
2201 @chapter Non-portable Extensions to Iterate (Contribs)
2202
2203 Currently, there is only one non-portable extension to iterate in the
2204 distribution: @code{iterate-pg}. If you have made an extension that
2205 depends on non-portable features, feel free to send them to
2206 the @iter{} project team for inclusion in the iterate distribution.
2207
2208 @section An SQL Query Driver for Iterate
2209
2210 The pg package by Eric Marsden (see @url{http://cliki.net/pg})
2211 provides an interface to the PostgreSQL database. Using the
2212 @code{in-relation} driver, it is possible to handle the results of SQL
2213 queries with @iter{}.
2214
2215 This usage example should give you an idea of how to use it:
2216
2217 @lisp
2218 (pg:with-pg-connection (c "somedb" "someuser")
2219 (iter (for (impl version date) in-relation "select * from version"
2220 on-connection *dbconn*)
2221 (collect version)))
2222 @end lisp
2223
2224 The distribution now contains an @file{iterate.asd} system definition
2225 file for the @iter{} package.
2226 To use the extension via @acronym{ASDF, Another System Definition
2227 Facility}, simply make your system depend on the @code{iterate-pg}
2228 system instead of the @code{iterate} system. To load it manually,
2229 use:
2230
2231 @lisp
2232 (asdf:oos 'asdf:load-op :iterate-pg)
2233 @end lisp
2234
2235 @c ===================================================================
2236 @node Obtaining Iterate
2237 @chapter Obtaining @code{Iterate}
2238
2239 @iter{} has been successfully ported to most implementations that
2240 purport to conform to ANSI CL. Since 2006, source and project
2241 information is available from
2242 @url{http://common-lisp.net/project/iterate/}. The mailing list for
2243 all purposes is @email{iterate-devel@@common-lisp.net}, but you need
2244 to subscribe to it before posting.
2245
2246 The source file was split into two files in 2003: @file{package.lisp}
2247 contains the package definition, @file{iterate.lisp} the main code.
2248 Other files in the distribution contain user contributions, test cases
2249 and documentation.
2250
2251 @iter{} resides in the @code{iterate} package (nickname @code{iter}).
2252 Just say @code{(use-package :iterate)} to make all the necessary
2253 symbols available. If a symbol is not exported, it appears in this
2254 manual with an ``@code{iterate::}'' prefix.
2255
2256 The regression test suite in @file{iterate-test.lisp}, based on
2257 @acronym{MIT}'s @code{RT} package, contains many examples.
2258
2259 @quotation Note
2260 The rest of this chapter serves history.
2261 @end quotation
2262
2263 @iter{} currently runs on Lisp Machines, and on HP's, Sun3's and
2264 Sparcstations under Lucid. @iter{} source and binaries are available
2265 at the @acronym{MIT} @acronym{AI} Lab in the subdirectories of
2266 @file{/src/local/lisplib/}.
2267 The source file, @code{iterate.lisp}, is also available for anonymous
2268 FTP in the directory @file{/com/ftp/pub/} on the machine
2269 @code{TRIX.AI.MIT.EDU} (Internet number 128.52.32.6). If you are
2270 unable to obtain @code{iterate} in one of these ways, send mail to
2271 @email{jba@@ai.mit.edu} and I will send you the source file.
2272
2273 Send bug reports to @email{bug-iterate@@ai.mit.edu}. The
2274 @code{info-iterate} mailing list will have notices of changes and
2275 problems; to have yourself added, send mail to
2276 @email{info-iterate-request@@ai.mit.edu}.
2277
2278 @c ===================================================================
2279 @node Acknowledgements
2280 @chapter Acknowledgements
2281
2282 Richard Waters provided invaluable criticism which spurred me to
2283 improve @iter{} greatly. As early users, David Clemens, Oren Etzioni
2284 and Jeff Siskind helped ferret out many bugs.
2285
2286 Thanks to Andreas Fuch, J@"org H@"ohle and Attila Lendvai, who more
2287 than a decade after the original release, ported the code to ANSI CL
2288 and fixed long-standing bugs.
2289
2290 @c ===================================================================
2291 @node Don't Loop Iterate
2292 @appendix Don't Loop, Iterate
2293
2294 @quotation Note
2295 This appendix is a Texinfo conversion performed by Lu@'{@dotless{i}}s
2296 Oliveira of Jonathan Amsterdam's Working Paper 324, MIT AI Lab
2297 entitled ``Don't Loop, Iterate.''
2298 @end quotation
2299
2300 @section Introduction
2301
2302 Above all the wonders of Lisp's pantheon stand its metalinguistic
2303 tools; by their grace have Lisp's acolytes been liberated from the
2304 rigid asceticism of lesser faiths. Thanks to Macro and kin, the
2305 jolly, complacent Lisp hacker can gaze through a fragrant cloud of
2306 setfs and defstructs at the emaciated unfortunates below, scraping out
2307 their meager code in inflexible notation, and sneer superciliously.
2308 It's a good feeling.
2309
2310 But all's not joy in Consville. For---I beg your pardon, but---there
2311 really is no good way to @emph{iterate} in Lisp. Now, some are happy
2312 to map their way about, whether for real with @code{mapcar} and
2313 friends, or with the make-believe of Series; others are so satisfied
2314 with @code{do} it's a wonder they're not C hackers.@footnote{Hey,
2315 don't get mad---I'll be much more polite later, when the real paper
2316 starts.} Still others have gotten by with @code{loop}, but are
2317 getting tired of looking up the syntax in the manual over and over
2318 again. And in the elegant schemes of some, only tail recursion and
2319 lambdas figure. But that still leaves a sizeable majority of
2320 folk---well, me, at least---who would simply like to @emph{iterate},
2321 thank you, but in a way that provides nice abstractions, is
2322 extensible, and looks like honest-to-God Lisp.
2323
2324 In what follows I describe a macro package, called @iter{}, that
2325 provides the power and convenient abstractions of @code{loop} but in a
2326 more syntactically palatable way. @code{iter} also has many features
2327 that @code{loop} lacks, like generators and better support for nested
2328 loops. @iter{} generates inline code, so it's more efficient than
2329 using the higher-order function approach. And @iter{} is also
2330 extensible---it's easy to add new clauses to its vocabulary in order
2331 to express new patterns of iteration in a convenient way.
2332
2333 @c \iter\ is fully documented in AI Lab Memo No.@: 1236, \iman.
2334
2335 @section More about @iter{}
2336
2337 A Common Lisp programmer who wonders what's lacking with present-day
2338 iteration features would do well to consider @code{setf}. Of course,
2339 @code{setf} doesn't iterate, but it has some other nice properties.
2340 It's easy to use, for one thing. It's extensible---you can define new
2341 @code{setf} methods very easily, so that @code{setf} will work with
2342 new forms. @code{setf} is also efficient, turning into code that's as
2343 good as anyone could write by hand. Arguably, @code{setf} provides a
2344 nice abstraction: it allows you to view value-returning forms, like
2345 @code{(car @dots{})} or @code{(get @dots{})} as locations that can be
2346 stored into. Finally and most obviously, @code{setf} @emph{looks}
2347 like Lisp; it's got a syntax right out of @code{setq}.
2348
2349 @iter{} attempts to provide all of these properties. Here is a simple
2350 use of @iter{} that returns all the elements of @code{num-list} that
2351 are greater than three:
2352
2353 @lisp
2354 (iterate (for el in num-list)
2355 (when (> el 3)
2356 (collect el)))
2357 @end lisp
2358
2359 An @iter{} form consists of the symbol @iter{} followed by some Lisp
2360 forms. Any legal Lisp form is allowed, as well as certain forms that
2361 @iter{} treats specially, called @emph{clauses}. @code{for@dots{}in}
2362 and @code{collect} are the two clauses in the above example. An
2363 @iter{} clause can appear anywhere a Lisp form can appear; @iter{}
2364 walks its body, looking inside every form, processing @iter{} clauses
2365 when it finds them. It even expands macros, so you can write macros
2366 that contain @iter{} clauses. Almost all clauses use the syntax of
2367 function keyword-argument lists: alternating keywords and arguments.
2368 @iter{} keywords don't require a preceding colon, but you can use one
2369 if you like.
2370
2371 @iter{} provides many convenient iteration abstractions, most of them
2372 familiar to @code{loop} users. Iteration-driving clauses (those
2373 beginning with @code{for}) can iterate over numbers, lists, arrays,
2374 hashtables, packages and files. There are clauses for collecting
2375 values into a list, summing and counting, maximizing, finding maximal
2376 elements, and various other things. Here are a few examples, for
2377 extra flavor.
2378
2379 To sum a list of numbers:
2380
2381 @lisp
2382 (iterate (for i in list)
2383 (sum i))
2384 @end lisp
2385
2386 To find the length of the shortest element in a list:
2387
2388 @lisp
2389 (iterate (for el in list)
2390 (minimize (length el)))
2391 @end lisp
2392
2393 To find the shortest element in a list:
2394
2395 @lisp
2396 (iterate (for el in list)
2397 (finding el minimizing (length el)))
2398 @end lisp
2399
2400 To return @code{t} only if every other element of a list is odd:
2401
2402 @lisp
2403 (iterate (for els on list by #'cddr)
2404 (always (oddp (car els))))
2405 @end lisp
2406
2407 To split an association list into two separate lists (this example
2408 uses @iter{}'s ability to do destructuring):
2409
2410 @lisp
2411 (iterate (for (key . item) in alist)
2412 (collect key into keys)
2413 (collect item into items)
2414 (finally (return (values keys items))))
2415 @end lisp
2416
2417 @section Comparisons With Other Iteration Methods
2418
2419 As with any aspect of coding, how to iterate is a matter of taste. I
2420 do not wish to dictate taste or even to suggest that @iter{} is a
2421 ``better'' way to iterate than other methods. I would, however, like
2422 to examine the options, and explain why I prefer @iter{} to its
2423 competitors.
2424
2425 @subsection @code{do}, @code{dotimes} and @code{dolist}
2426
2427 The @code{do} form has long been a Lisp iteration staple. It provides
2428 for binding of iteration variables, an end-test, and a body of
2429 arbitrary code. It can be a bit cumbersome for simple applications,
2430 but the most common special cases---iterating over the integers from
2431 zero and over the members of a list---appear more conveniently as
2432 @code{dotimes} and @code{dolist}.
2433
2434 @code{do}'s major problem is that it provides no abstraction. For
2435 example, collection is typically handled by binding a variable to
2436 @code{nil}, pushing elements onto the variable, and @code{nreverse}ing
2437 the result before returning it. Such a common iteration pattern
2438 should be easier to write. (It is, using @code{mapcar}---but see
2439 below.)
2440
2441 Another problem with @code{do}, for me at least, is that it's hard to
2442 read. The crucial end-test is buried between the bindings and the
2443 body, marked off only by an extra set of parens (and some
2444 indentation). It is also unclear, until after a moment of
2445 recollection, whether the end-test has the sense of a ``while'' or an
2446 ``until.''
2447
2448 Despite its flaws, @code{do} is superior to the iteration facilities
2449 of every other major programming language except CLU. Perhaps that is
2450 the reason many Lisp programmers don't mind using it.
2451
2452 @subsection Tail Recursion
2453 @c FIXME: removed citation due to laziness
2454
2455 Tail-recursive implementations of loops, like those found in Scheme
2456 code [SchemeBook], are parsimonious and illuminating. They have the
2457 advantage of looking like recursion, hence unifying the notation for
2458 two different types of processes. For example, if only tail-recursion
2459 is used, a loop that operates on list elements from front to back
2460 looks very much like a recursion that operates on them from back to
2461 front.
2462
2463 However, using tail-recursion exclusively can lead to cumbersome code
2464 and a proliferation of functions, especially when one would like to
2465 embed a loop inside a function. Tail-recursion also provides no
2466 abstraction for iteration; in Scheme, that is typically done with
2467 higher-order functions.
2468
2469 @subsection High-order Functions
2470
2471 Lisp's age-old mapping functions, recently revamped for Common Lisp
2472 [CLM], are another favorite for iteration. They provide a pleasing
2473 abstraction, and it's easy to write new higher-order functions to
2474 express common iteration patterns. Common Lisp already comes with
2475 many such useful functions, for removing, searching, and performing
2476 reductions on lists. Another Common Lisp advantage is that these
2477 functions work on any sequence---vectors as well as lists.
2478
2479 One problem with higher-order functions is that they are inefficient,
2480 requiring multiple calls on their argument function. While the the
2481 built-ins, like @code{map} and @code{mapcar}, can be open-coded, that
2482 cannot be so easily done for user-written functions. Also, using
2483 higher-order functions often results in the creation of intermediate
2484 sequences that could be avoided if the iteration were written out
2485 explicitly.
2486
2487 The second problem with higher-order functions is very much a matter
2488 of personal taste. While higher-order functions are theoretically
2489 elegant, they are often cumbersome to read and write. The unpleasant
2490 sharp-quote required by Common Lisp is particularly annoying here, and
2491 even in Scheme, I find the presence of a lambda with its argument list
2492 visually distracting.
2493
2494 Another problem is that it's difficult to express iteration of
2495 sequences of integers without creating such sequences explicitly as
2496 lists or arrays. One could resort to tail-recursion or
2497 @code{dotimes}---but then it becomes very messy to express double
2498 iterations where one driver is over integers. Multiple iteration is
2499 easy in @iter{}, as illustrated by the following example, which creates
2500 an alist of list elements and their positions:
2501
2502 @lisp
2503 (iterate (for el in list)
2504 (for i from 0)
2505 (collect (cons el i)))
2506 @end lisp
2507
2508 @subsection Streams and Generators
2509
2510 For really heavy-duty iteration jobs, nothing less than a
2511 coroutine-like mechanism will do. Such mechanisms hide the state of
2512 the iteration behind a convenient abstraction. A @emph{generator} is
2513 a procedure that returns the next element in the iteration each time
2514 it is called. A @emph{stream} (in the terminology of [SchemeBook]) is
2515 a data structure which represents the iteration, but which computes
2516 the next element only on demand. Generators and streams support a
2517 similar style of programming. Here, for example, is how you might
2518 enumerate the leaves of a tree (represented as a Lisp list with atoms
2519 at the leaves) using streams:
2520
2521 @lisp
2522 (defun tree-leaves (tree)
2523 (if (atom tree)
2524 (stream-cons tree empty-stream)
2525 (stream-append (tree-leaves (car tree))
2526 (tree-leaves (cdr tree)))))
2527 @end lisp
2528
2529 Although @code{tree-leaves} looks like an ordinary recursion, it will
2530 only do enough work to find the first leaf before returning. The
2531 stream it returns can be accessed with @code{stream-car}, which will
2532 yield the (already computed) first leaf of the tree, or with
2533 @code{stream-cdr}, which will initiate computation of the next leaf.
2534
2535 Such a computation would be cumbersome to write using @iter{}, or any
2536 of the other standard iteration constructs; in fact, it is not even
2537 technically speaking an iteration, if we confine that term to
2538 processes that take constant space and linear time. Streams, then,
2539 are definitely more powerful than standard iteration machinery.
2540
2541 Unfortunately, streams are very expensive, since they must somehow
2542 save the state of the computation. Generators are typically cheaper,
2543 but are less powerful and still require at least a function call. So
2544 these powerful tools should be used only when necessary, and that is
2545 not very often; most of the time, ordinary iteration suffices.
2546
2547 There is one aspect of generators that @iter{} can capture, and that
2548 is the ability to produce elements on demand. Say we wish to create
2549 an alist that pairs the non-null elements of a list with the positive
2550 integers. We saw above that it is easy to iterate over a list and a
2551 series of numbers simultaneously, but here we would like to do
2552 something a little different: we want to iterate over the list of
2553 elements, but only draw a number when we need one (namely, when a list
2554 element is non-null). The solution employs the @iter{} @code{generate}
2555 keyword in place of @code{for} and the special clause @code{next}:
2556
2557 @lisp
2558 (iterate (for el in list)
2559 (generate i from 1)
2560 (if el
2561 (collect (cons el (next i)))))
2562 @end lisp
2563
2564 Using @code{next} with any driver variable changes how that driver
2565 works. Instead of supplying its values one at a time on each
2566 iteration, the driver computes a value only when a @code{next} clause
2567 is executed. This ability to obtain values on demand greatly
2568 increases @iter{}'s power. Here, @code{el} is set to the next element
2569 of the list on each iteration, as usual; but @code{i} is set only when
2570 @code{(next i)} is executed.
2571
2572 @subsection Series
2573
2574 Richard C. Waters has developed a very elegant notation called Series
2575 which allows iteration to be expressed as sequence-mapping somewhat in
2576 the style of APL, but which compiles to efficient looping code
2577 [Series].
2578
2579 My reasons for not using Series are, again, matters of taste. Like
2580 many elegant notations, Series can be somewhat cryptic. Understanding
2581 what a Series expression does can require some effort until one has
2582 mastered the idiom. And if you wish to share your code with others,
2583 they will have to learn Series as well. @iter{} suffers from this
2584 problem to some extent, but since the iteration metaphor it proposes
2585 is much more familiar to most programmers than that of Series, it is
2586 considerably easier to learn and read.
2587
2588 @subsection @code{Prog} and @code{Go}
2589
2590 Oh, don't be silly.
2591
2592 @subsection @code{Loop}
2593
2594 @code{loop} is the iteration construct most similar to @iter{} in
2595 appearance. @code{loop} is a macro written originally for MacLisp and
2596 in widespread use [Loop]. It has been adopted as part of Common Lisp.
2597 @code{loop} provides high-level iteration with abstractions for
2598 collecting, summing, maximizing and so on. Recall our first @iter{}
2599 example:
2600
2601 @lisp
2602 (iterate (for el in num-list)
2603 (when (> el 3)
2604 (collect el)))
2605 @end lisp
2606
2607 Expressed with @code{loop}, it would read
2608
2609 @lisp
2610 (loop for el in list
2611 when (> el 3)
2612 collect el)
2613 @end lisp
2614
2615 The similarity between the two macros should immediately be apparent.
2616 Most of @iter{}'s clauses were borrowed from @code{loop}. But
2617 compared to @iter{}, @code{loop} has a paucity of parens. Though
2618 touted as more readable than heavily-parenthesized code, @code{loop}'s
2619 Pascalish syntax creates several problems. First, many
2620 dyed-in-the-wool Lisp hackers simply find it ugly. Second, it
2621 requires learning the syntax of a whole new sublanguage. Third, the
2622 absence of parens makes it hard to parse, both by machine and, more
2623 importantly, by human. Fourth, one often has to consult the manual to
2624 recall lesser-used aspects of the strange syntax. Fifth, there is no
2625 good interface with the rest of Lisp, so @code{loop} clauses cannot
2626 appear inside Lisp forms and macros cannot expand to pieces of
2627 @code{loop}. And Sixth, pretty-printers and indenters that don't know
2628 about @code{loop} will invariably display it wrongly. This is
2629 particularly a problem with program-editor indenters. A reasonably
2630 clever indenter, like that of Gnu Emacs, can indent nearly any normal
2631 Lisp form correctly, and can be easily customized for most new forms.
2632 But it can't at present handle @code{loop}. The syntax of @iter{} was
2633 designed to keep parens to a minimum, but conform close enough to Lisp
2634 so as not to confuse code-display tools. Gnu Emacs indents @iter{}
2635 reasonably with no modifications.
2636
2637 Indenting is a mere annoyance; @code{loop}'s lack of extensibility is
2638 a more serious problem. The original @code{loop} was completely
2639 extensible, but the Symbolics version only provides for the definition
2640 of new iteration-driving clauses, and the Common Lisp specification
2641 does not have any extension mechanism. But extensibility is a boon.
2642 Consider first the problem of adding the elements of a list together,
2643 which can be accomplished with @iter{} by
2644
2645 @lisp
2646 (iterate (for el in list)
2647 (sum el))
2648 @end lisp
2649
2650 and in @code{loop} with
2651
2652 @lisp
2653 (loop for el in list
2654 sum el)
2655 @end lisp
2656
2657 But now, say that you wished to compute the sum of the square roots of
2658 the elements. You could of course write, in either @code{loop} or
2659 @iter{},
2660
2661 @lisp
2662 (iterate (for el in list)
2663 (sum (sqrt el)))
2664 @end lisp
2665
2666 But perhaps you find yourself writing such loops often enough to make
2667 it worthwhile to create a new abstraction. There is nothing you can
2668 do in @code{loop}, but in @iter{} you could simply write a macro:
2669
2670 @lisp
2671 (defmacro (sum-of-sqrts expr &optional into-var)
2672 `(sum (sqrt ,expr) into ,into-var))
2673 @end lisp
2674
2675 @code{sum-of-sqrts} is a perfectly ordinary Lisp macro. Since @iter{}
2676 expands all macros and processes the results, @code{(sum-of-sqrts el)}
2677 will behave exactly as if we'd written @code{(sum (sqrt el))}.
2678
2679 There's also a way to define macros that use @iter{}'s clause syntax.
2680 @c removed citation again
2681
2682 @c Just to beat a dead horse, I'd like to point out that there's no
2683 @c way to define {\lisp for...maximizing} in \looP.\footnote{In fact,
2684 @c it was in part the frustration of knowing that \looP\ could
2685 @c generate code to maximize a value, but could not be easily altered
2686 @c to supply the element associated with that maximum, that prompted
2687 @c me to write \iter.}
2688
2689 @section Implementation
2690
2691 A Common Lisp implementation of @iter{} has existed for well over a
2692 year. It runs under Lucid for HP 300's, Sun 3's and SPARCstations,
2693 and on Symbolics Lisp machines.
2694 @c See \iman\ for details.
2695
2696 @section Conclusion
2697
2698 Iteration is a matter of taste. I find @iter{} more palatable than
2699 other iteration constructs: it's more readable, more efficient than
2700 most, provides nice abstractions, and can be extended.
2701
2702 If you're new to Lisp iteration, start with @iter{}---look before you
2703 @code{loop}. If you're already using @code{loop} and like the power
2704 that it offers, but have had enough of its syntax and inflexibility,
2705 then my advice to you is, don't @code{loop}---@iter{}.
2706
2707 @section Acknowledgments
2708
2709 Thanks to David Clemens for many helpful suggestions and for the
2710 egregious pun near the end. Conversations with Richard Waters
2711 prompted me to add many improvements to @iter{}. Alan Bawden, Sundar
2712 Narasimhan, and Jerry Roylance also provided useful comments. David
2713 Clemens and Oren Etzioni shared with me the joys of beta-testing.
2714
2715 @section Bibliography
2716
2717 @itemize
2718 @item
2719 [SchemeBook] Abelson, Harold and Gerald Jay Sussman. @emph{Structure
2720 and Interpretation of Computer Programs.} Cambridge, MA: The MIT
2721 Press, 1985.
2722
2723 @item
2724 [Loop] ``The loop Iteration Macro.'' In @emph{Symbolics Common
2725 Lisp---Language Concepts}, manual 2A of the Symbolics documentation,
2726 pp.@: 541--567.
2727
2728 @item
2729 [CLM] Steele, Guy L@. @emph{Common Lisp: The Language}. Bedford, MA:
2730 Digital Press, 1984.
2731
2732 @item
2733 [Series] Waters, Richard C@. @emph{Optimization of Series Expressions:
2734 Part I: User's Manual for the Series Macro Package}. MIT AI Lab Memo
2735 No.@: 1082.
2736 @end itemize
2737
2738 @c ===================================================================
2739 @node Comprehensive Index
2740 @unnumbered Index
2741 @printindex cp
2742
2743 @bye