ジェネレータ(英: generator)は、計算機科学の分野において、繰り返し動作の振る舞いを制御するために用いられる特殊なサブルーチンである。ジェネレータは、パラメータを持ち、呼び出し可能で、値の列を持つという点で配列を返す関数と非常に良く似ている。
しかし、すべての要素を一度に計算し配列を構築するのではなく、ジェネレータは一度に一つの値しか生成しない。これによりわずかしかメモリを消費せず、呼び出し側は最初の一部の値を用いて即座に処理を開始できる。そのため、ジェネレータの実装に遅延評価を用いることができる場合もある。
しかし、ジェネエレータは参照透過ではない。簡単に言えば、ジェネレータは関数に類似しているが、イテレータのように振舞う。
In computer science, a generator is a special routine that can be used to control the iteration behaviour of a loop.
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 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 also a generalisation of subroutines, but are more limited than coroutines. Specifically, while both of these can yield multiple times, suspending their execution and allowing re-entry at multiple entry points, they differ in that coroutines can control where execution continues after they yield, while generators cannot, instead transferring control back to the generator's caller.
That is, since generators are primarily used to simplify the writing of iterators, the yield statement in a generator does not specify a coroutine to jump to, but rather passes a value back to a parent routine.
However, it is still possible to implement coroutines on top of a generator facility, with the aid of a top-level dispatcher routine (a trampoline, essentially) that passes control explicitly to child generators identified by tokens passed back from the generators: