Next: , Up: loops generators   [Index]


1.16.4.1 Introduction to generators

This section defines the syntax ?generator. Each generator defines a sequence of bindings through which one or more variables are run. The scope of the variables begins after the closing parenthesis of the generator expression and extends to the end of the comprehension it is part of.

The variables defined by the generators are specified using the syntax:

?vars -> ?variable1
       |  ?variable1 (index ?variable2)

where ?variable1 runs through the values in the sequence defined by the generator, and the optional ?variable2 is an exact integer–valued index variable counting the values (starting from 0). The names of the variables must be distinct. The following example illustrates the index variable:

(list-ec (: x (index i) "abc")
   (list x i))
⇒ ((#\a 0) (#\b 1) (#\c 2))

Unless defined otherwise, all generators make sure that the expressions provided for their syntactic arguments are evaluated exactly once, before enumeration begins. Moreover, it may be assumed that the generators do not copy the code provided for their arguments, because that could lead to exponential growth in code size.

Finally, it is possible to assign a value to the variables defined by a generator, but the effect of this assignment is unspecified; example:

(list-ec (:range i 5)
  (set! i #\a)          ;undefined behaviour because of this
  ---)