Generators
Another way to write the downToOne
function is to use a Generator. To instantiate a Generator
object, one must use the function *
declaration. Generators are functions that can be exited and later re-entered with its context (variable bindings) saved across re-entrances.
For example, the downToOne
function above can be rewritten as:
Generators return an iterable object. When the iterator's next()
function is called, it is executed until the first yield
expression, which specifies the value to be returned from the iterator or with yield*
, which delegates to another generator function. When a return
expression is called in the generator, it will mark the generator as done and pass back as the return value. Further calls to next()
will not return any new values.
Sample code
The yield*
expression enables a generator to call another generator function during iteration.