In computer science, a generator is a routine that can be used to control the iteration behaviour of a loop. All generators are also iterators.[1] A generator is very similar to a function that returns an array, in that a generator has parameters, can be called, and generates a sequence of values. However, instead of building an array containing all the values and returning them all at once, a generator yields the values one at a time, which requires less memory and allows the caller to get started processing the first few values immediately. In short, a generator looks like a function but behaves like an iterator.
Generators can be implemented in terms of more expressive control flow constructs, such as coroutines or first-class continuations.[2] Generators, also known as semicoroutines,[3] are a special case of (and weaker than) coroutines, in that they always yield control back to the caller (when passing a value back), rather than specifying a coroutine to jump to; see comparison of coroutines with generators.
Generators are usually invoked inside loops.[4] The first time that a generator invocation is reached in a loop, an iterator object is created that encapsulates the state of the generator routine at its beginning, with arguments bound to the corresponding parameters. The generator's body is then executed in the context of that iterator until a special yield action is encountered; at that time, the value provided with the yield action is used as the value of the invocation expression. The next time the same generator invocation is reached in a subsequent iteration, the execution of the generator's body is resumed after the yield action, until yet another yield action is encountered. In addition to the yield action, execution of the generator body can also be terminated by a finish action, at which time the innermost loop enclosing the generator invocation is terminated. In more complicated situations, a generator may be used manually outside of a loop to create an iterator, which can then be used in various ways.
Because generators compute their yielded values only on demand, they are useful for representing streams, such as sequences that would be expensive or impossible to compute at once. These include e.g. infinite sequences and live data streams.
When eager evaluation is desirable (primarily when the sequence is finite, as otherwise evaluation will never terminate), one can either convert to a list, or use a parallel construction that creates a list instead of a generator. For example, in Python a generator g
can be evaluated to a list l
via l = list(g)
, while in F# the sequence expression seq { ... }
evaluates lazily (a generator or sequence) but [ ... ]
evaluates eagerly (a list).
In the presence of generators, loop constructs of a language – such as for and while – can be reduced into a single loop ... end loop construct; all the usual loop constructs can then be comfortably simulated by using suitable generators in the right way. For example, a ranged loop like for x = 1 to 10
can be implemented as iteration through a generator, as in Python's for x in range(1, 10)
. Further, break
can be implemented as sending finish to the generator and then using continue
in the loop.
Generators first appeared in CLU (1975),[5] were a prominent feature in the string manipulation language Icon (1977) and are now available in Python (2001),[6] C#,[7] Ruby, PHP,[8] ECMAScript (as of ES6/ES2015), and other languages. In CLU and C#, generators are called iterators, and in Ruby, enumerators.
The final Common Lisp standard does not natively provide generators, yet various library implementations exist, such as SERIES documented in CLtL2 or pygen.
A yield statement is used to implement iterators over user-defined data abstractions.[9]
for c: char in string_chars(s) do ...end;
Every expression (including loops) is a generator. The language has many generators built-in and even implements some of the logic semantics using the generator mechanism (logical disjunction or "OR" is done this way).
Printing squares from 0 to 20 can be achieved using a co-routine by writing:
However, most of the time custom generators are implemented with the "suspend" keyword which functions exactly like the "yield" keyword in CLU.
C does not have generator functions as a language construct, but, as they are a subset of coroutines, it is simple to implement them using any framework that implements stackful coroutines, such as libdill.[10] On POSIX platforms, when the cost of context switching per iteration is not a concern, or full parallelism rather than merely concurrency is desired, a very simple generator function framework can be implemented using pthreads and pipes.
It is possible to introduce generators into C++ using pre-processor macros. The resulting code might have aspects that are very different from native C++, but the generator syntax can be very uncluttered.[11] The set of pre-processor macros defined in this source allow generators defined with the syntax as in the following example:
This can then be iterated using:
Moreover, C++11 allows foreach loops to be applied to any class that provides the begin
and end
functions. It's then possible to write generator-like classes by defining both the iterable methods (begin
and end
) and the iterator methods (operator!=
, operator++
and operator*
) in the same class. For example, it is possible to write the following program:
int main
A basic range implementation would look like that:
Perl does not natively provide generators, but support is provided by the Coro::Generator module which uses the Coro co-routine framework. Example usage:
use Coro::Generator;
my $chars = ['A'...'Z'];
my $letters = generator ;
print $letters->, "\n" for (0..15);
Example parallel to Icon uses Raku (formerly/aka Perl 6) Range class as one of several ways to achieve generators with the language.
Printing squares from 0 to 20 can be achieved by writing:
However, most of the time custom generators are implemented with "gather" and "take" keywords in a lazy context.
In Tcl 8.6, the generator mechanism is founded on named coroutines.
set count [generator { for {set i 10} {$i <= 20} {incr i} { yield $i } }]
while 1
In Haskell, with its lazy evaluation model, every datum created with a non-strict data constructor is generated on demand. For example,
from10to20 :: [Integer]from10to20 = takeWhile (<= 20) $ countFrom 10
primes :: [Integer]primes = 2 : 3 : nextPrime 5 where nextPrime n | notDivisible n = n : nextPrime (n + 2) | otherwise = nextPrime (n + 2) notDivisible n = all ((/= 0) . (rem n)) $ takeWhile ((<= n) . (^ 2)) $ tail primeswhere (:)
is a non-strict list constructor, cons, and $
is just a "called-with" operator, used for parenthesization. This uses the standard adaptor function,
Racket provides several related facilities for generators. First, its for-loop forms work with sequences, which are a kind of a producer:
But more directly, Racket comes with a generator library for a more traditional generator specification. For example,
(require racket/generator)(define (ints-from from) (generator (for ([i (in-naturals from)]) ; infinite sequence of integers from 0 (yield i))))(define g (ints-from 10))(list (g) (g) (g)) ; -> '(10 11 12)Note that the Racket core implements powerful continuation features, providing general (re-entrant) continuations that are composable, and also delimited continuations. Using this, the generator library is implemented in Racket.
The community of PHP implemented generators in PHP 5.5. Details can be found in the original Request for Comments: Generators.
Infinite Fibonacci sequence:
foreach (fibonacci as $number)
Fibonacci sequence with limit:
foreach (fibonacci(10) as $number)
Any function which contains a
yield statement is automatically a generator function.Ruby supports generators (starting from version 1.9) in the form of the built-in Enumerator class.
chars = Enumerator.new(['A', 'B', 'C', 'Z'])
4.times
count = Enumerator.new do |yielder| i = 0 loop end
100.times
Java has had a standard interface for implementing iterators since its early days, and since Java 5, the "foreach" construction makes it easy to loop over objects that provide the java.lang.Iterable
interface. (The Java collections framework and other collections frameworks, typically provide iterators for all collections.)
record Pair(int a, int b) ;
Iterable
myIterable.forEach(System.out::println);
Or get an Iterator from the Java 8 super-interface BaseStream of Stream interface.
record Pair(int a, int b) ;
// Save the iterator of a stream that generates fib sequenceIterator
// Print the first 5 elementsfor (int i = 0; i < 5; i++)
System.out.println("done with first iteration");
// Print the next 5 elementsfor (int i = 0; i < 5; i++)
Output:
An example C# 2.0 generator (the yield
is available since C# version 2.0):Both of these examples utilize generics, but this is not required. yield keyword also helps in implementing custom stateful iterations over a collection as discussed in this discussion.[12]
It is possible to use multiple yield return
statements and they are applied in sequence on each iteration:
In XL, iterators are the basis of 'for' loops:
iterator IntegerIterator (var out Counter : integer; Low, High : integer) written Counter in Low..High is Counter := Low while Counter <= High loop yield Counter += 1
// Note that I needs not be declared, because declared 'var out' in the iterator// An implicit declaration of I as an integer is therefore made herefor I in 1..5 loop IO.WriteLn "I=", I
F# provides generators via sequence expressions, since version 1.9.1.[13] These can define a sequence (lazily evaluated, sequential access) via seq { ... }
, a list (eagerly evaluated, sequential access) via [ ... ]
or an array (eagerly evaluated, indexed access) via [| ... |]
that contain code that generates values. For example,
Generators were added to Python in version 2.2 in 2001.[6] An example generator:
def countfrom(n: int) -> Iterator[int]: while True: yield n n += 1
for i in countfrom(10): if i <= 20: print(i) else: break
import itertools
def primes -> Iterator[int]: """Generate prime numbers indefinitely as needed.""" yield 2 n = 3 p = [2] while True: # If dividing n by all the numbers in p, up to and including sqrt(n), # produces a non-zero remainder then n is prime. if all(n % f > 0 for f in itertools.takewhile(lambda f: f * f <= n, p)): yield n p.append(n) n += 2
In Python, a generator can be thought of as an iterator that contains a frozen stack frame. Whenever next
is called on the iterator, Python resumes the frozen frame, which executes normally until the next yield
statement is reached. The generator's frame is then frozen again, and the yielded value is returned to the caller.
PEP 380 (implemented in Python 3.3) adds the yield from
expression, allowing a generator to delegate part of its operations to another generator or iterable.[14]
Python has a syntax modeled on that of list comprehensions, called a generator expression that aids in the creation of generators.The following extends the first example above by using a generator expression to compute squares from the countfrom
generator function:
for j in squares: if j <= 20: print(j) else: break
ECMAScript 6 (a.k.a. Harmony) introduced generator functions.
An infinite Fibonacci sequence can be written using a function generator:
// bounded by upper limit 10for (const n of fibonacci(10))
// generator without an upper bound limitfor (const n of fibonacci)
// manually iteratinglet fibGen = fibonacci;console.log(fibGen.next.value); // 1console.log(fibGen.next.value); // 1console.log(fibGen.next.value); // 2console.log(fibGen.next.value); // 3console.log(fibGen.next.value); // 5console.log(fibGen.next.value); // 8
// picks up from where you stoppedfor (const n of fibGen)
The iterators package can be used for this purpose.[15] [16]
abc <- iter(c('a','b','c'))nextElem(abc)
Example in Pharo Smalltalk:
The Golden ratio generator below returns to each invocation 'goldenRatio next' a better approximation to the Golden Ratio.
goldenRatio next.
The expression below returns the next 10 approximations.
See more in A hidden gem in Pharo: Generator.