Generator (computer programming)


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. 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. Generators, also known as semicoroutines, are a special case of coroutines, in that they always yield control back to the caller, rather than specifying a coroutine to jump to; see comparison of coroutines with generators.

Uses

Generators are usually invoked inside loops. 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, 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, while in F# the sequence expression seq evaluates lazily but evaluates eagerly.
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. Further, break can be implemented as sending finish to the generator and then using continue in the loop.

Timeline

Generators first appeared in CLU, were a prominent feature in the string manipulation language Icon and are now available in Python, C#, Ruby, the later versions of ECMAScript and other languages. In CLU and C#, generators are called iterators, and in Ruby, enumerators.

Lisp

The final Common Lisp standard does not natively provide generators, yet various library implementations exist, such as documented in CLtL2 or .

CLU

A yield statement is used to implement iterators over user-defined data abstractions.

string_chars = iter yields ;
index: int := 1;
limit: int := string$size ;
while index <= limit do
yield ;
index := index + 1;
end;
end string_chars;
for c: char in string_chars do
...
end;

Icon

Every expression is a generator. The language has many generators built-in and even implements some of the logic semantics using the generator mechanism.
Printing squares from 0 to 20 can be achieved using a co-routine by writing:

local squares, j
squares := create
every j := |@squares do
if j <= 20 then
write
else
break

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.. 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.

C++

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. The set of pre-processor macros defined in this source allow generators defined with the syntax as in the following example:

$generator

This can then be iterated using:

int main

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 and the iterator methods in the same class. For example, it is possible to write the following program:

  1. include
int main

A basic range implementation would look like that:

class range

Perl

Perl does not natively provide generators, but support is provided by the module which uses the co-routine framework. Example usage:

use strict;
use warnings;
  1. Enable generator and yield
use Coro::Generator;
  1. Array reference to iterate over
my $chars = ;
  1. New generator which can be called like a coderef.
my $letters = generator ;
  1. Call the generator 15 times.
print $letters->, "\n" for ;

Tcl

In Tcl 8.6, the generator mechanism is founded on named coroutines.

proc generator
  1. Use a simple 'for' loop to do the actual generation
set count
  1. Pull values from the generator until it is exhausted
while 1

Haskell

In Haskell, with its lazy evaluation model, everything is a generator - every datum created with a non-strict data constructor is generated on demand. For example,

countfrom n = n : countfrom
-- Example use: printing out the integers from 10 to 20.
test1 = mapM_ print $ takeWhile $ countfrom 10
primes = 2 : 3 : nextprime 5 where
nextprime n | b = n : nextprime
| otherwise = nextprime
where b = all.) $ takeWhile.) $ tail primes

where is a non-strict list constructor, cons, and $ is just a "called-with" operator, used for parenthesization. This uses the standard adaptor function,

takeWhile p =
takeWhile p | p x = x : takeWhile p xs
| otherwise =

which re-fetches values agreeable with a predicate, and stops requesting new values as soon as a non-agreeable one is encountered. The shared storage access is used as a universal mediator in Haskell. List comprehensions can be freely used:

test2 = mapM_ print $ takeWhile
test3 = mapM_ print

Racket

provides several related facilities for generators. First, its for-loop forms work with sequences, which are a kind of a producer:

)

and these sequences are also first-class values:

)

Some sequences are implemented imperatively and some are implemented as lazy lists. Also, new struct definitions can have a property that specifies how they can be used as sequences.
But more directly, Racket comes with a generator library for a more traditional generator specification. For example,

  1. lang racket

)))
) ; -> '

Note that the Racket core implements powerful continuation features, providing general continuations that are composable, and also delimited continuations. Using this, the generator library is implemented in Racket.

PHP

The community of PHP implemented generators in PHP 5.5. Details can be found in the original .

function Fibonacci
foreach

Any function which contains a yield statement is automatically a generator function.

Ruby

Ruby supports generators in the form of the built-in Enumerator class.

  1. Generator from an Enumerator object
chars = Enumerator.new
4.times
  1. Generator from a block
count = Enumerator.new do |yielder|
i = 0
loop
end
100.times

Java

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.
However, Java does not have generators built into the language. This means that creating iterators is often much trickier than in languages with built-in generators, especially when the generation logic is complex. Because all state must be saved and restored every time an item is to be yielded from an iterator, it is not possible to store state in local variables or use built-in looping routines, as when generators are available; instead, all of this must be manually simulated, using object fields to hold local state and loop counters.
Even simple iterators built this way tend to be significantly bulkier than those using generators, with a lot of boilerplate code.
The original example above could be written in Java 5 as:

// Iterator implemented as anonymous class. This uses generics but doesn't need to.
for

An infinite Fibonacci sequence could also be written in Java 5 as an Iterator:

Iterable fibo = new Iterable ;
// this could then be used as...
for

Also an infinite Fibonacci sequence could also be written using Java 8 Stream interface:

IntStream.generate.forEach;

Or get an Iterator from the Java 8 super-interface BaseStream of Stream interface.

public Iterable fibonacci
// this could then be used as...
for

C#

An example C# 2.0 generator :
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.

// Method that takes an iterable input
// and returns all even numbers.
public static IEnumerable GetEven

It is possible to use multiple yield return statements and they are applied in sequence on each iteration:

public class CityCollection : IEnumerable

XL

In XL, iterators are the basis of 'for' loops:

import IO = XL.UI.CONSOLE
iterator IntegerIterator 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 here
for I in 1..5 loop
IO.WriteLn "I=", I

F#

provides generators via sequence expressions, since version 1.9.1. These can define a sequence via seq , a list via or an array via that contain code that generates values. For example,

seq

forms a sequence of squares of numbers from 0 to 14 by filtering out numbers from the range of numbers from 0 to 25.

Python

Generators were added to Python in version 2.2 in 2001. An example generator:

from typing import Iterator
def countfrom -> Iterator:
while True:
yield n
n += 1
  1. Example use: printing out the integers from 10 to 20.
  2. Note that this iteration terminates normally, despite
  3. countfrom being written as an infinite loop.
for i in countfrom:
if i <= 20:
print
else:
break
  1. Another generator, which produces prime numbers indefinitely as needed.
import itertools
def primes -> Iterator:
yield 2
n = 3
p =
while True:
# If dividing n by all the numbers in p, up to and including sqrt,
# produces a non-zero remainder then n is prime.
if all:
yield n
p.append
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 adds the yield from expression, allowing a generator to delegate part of its operations to another generator or iterable.

Generator expressions

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:

squares =
for j in squares:
if j <= 20:
print
else:
break

ECMAScript

introduced generator functions.
An infinite Fibonacci sequence can be written using a function generator:

function* fibonacci
// bounded by upper limit 10
for
// generator without an upper bound limit
for )
// manually iterating
let fibGen = fibonacci;
console.log; // 1
console.log; // 1
console.log; // 2
console.log; // 3
console.log; // 5
console.log; // 8
// picks up from where you stopped
for

R

The iterators package can be used for this purpose.

library
  1. Example ------------------
abc <- iter
nextElem

Smalltalk

Example in Pharo Smalltalk:
The Golden ratio generator below returns to each invocation 'goldenRatio next' a better approximation to the Golden Ratio.

goldenRatio := Generator on: repeat
].
goldenRatio next.

The expression below returns the next 10 approximations.

Character cr join:.

See more in .