Download PDF file (284K characters) - Common

Transcript
Chapter 2: Clauses
6
To better understand the relationship between ordinary drivers and generators, observe
that we can rewrite an ordinary driver using its generator form immediately followed by
next, as this example shows:
(iter (generating i from 1 to 10)
(next i)
...)
Provided that the loop body contains no (next i) forms, this will behave just as if we
had written (for i from 1 to 10).
We can still refer to a driver variable v without using next; in this case, its value is that
given to it by the last evaluation of (next v ). Before (next v ) has been called the first
time, the value of v is undefined.
This semantics is more flexible than one in which v begins the loop bound to its first value
and calls of next supply subsequent values, because it means the loop will not terminate
too soon if the generator’s sequence is empty. For instance, consider the following code,
which tags non-nil elements of a list using a list of tags, and also counts the null elements.
(We assume there are at least as many tags as non-nil elements.)
(let* ((counter 0)
(tagged-list (iter (for el in list)
(generating tag in tag-list)
(if (null el)
(incf counter)
(collect (cons el (next tag)))))))
...)
It may be that there are just as many tags as non-null elements of list. If all the
elements of list are null, we still want the counting to proceed, even though tag-list is
nil. If tag had to be assigned its first value before the loop begins, we would have had
to terminate the loop before the first iteration, since when tag-list is nil, tag has no
first value. With the existing semantics, however, (next tag) will never execute, so the
iteration will cover all the elements of list.
When the “variable” of a driver clause is actually a destructuring template containing
several variables, all the variables are eligible for use with next. As before, (next v )
evaluates to v’s next value; but the effect is to update all of the template’s variables. For
instance, the following code will return the list (a 2 c).
(iter (generating (key . item) in ’((a . 1) (b . 2) (c . 3)))
(collect (next key))
(collect (next item)))
Only driver clauses with variables can be made into generators. This includes all clauses
mentioned so far except for repeat. It does not include for... previous, for... =,
for... initially... then or for... first... then (see below).
2.1.5 Previous Values of Driver Variables
Often one would like to access the value of a variable on a previous iteration. iterate
provides a special clause for accomplishing this.