generator
import "std/concurrency" (included in import "std") · namespace std.concurrency
A function that returns Iterator<T> and uses yield is a generator: the compiler turns its body into a Generator<T>, which runs it one yield at a time as a loop asks for values. You do not usually name these classes; they are what a generator is made of.
grav
import "std"
// The lines of a text that are not comments, numbered from 1.
fn code(text: string) -> Iterator<string> {
let n = 0
for (line in Str.lines(text)) {
n += 1
if (Str.startsWith(Str.trim(line), "#")) { continue }
yield "${n}: ${line}"
}
}
fn main() {
for (l in code("a = 1\n# note\nb = 2")) { print(l) }
}1: a = 1
3: b = 2How it runs:
- The body starts at the loop's first step and stops at each
yielduntil the next is asked for, so it never runs at the same time as the loop. Its locals keep their values between steps. - The body runs on a thread of its own, which costs a thread switch per value. That suits values that come from files, sockets, queries or long computations; for tight numeric loops, write an
Iterator<T>class or a plain loop. - A loop that stops early drops the generator: the paused
yieldthrowsGeneratorClosed, so the body'sfinallyblocks run and its thread ends. - An exception the body throws comes out of the loop step that was waiting for a value.
yieldbelongs to the function or method itself: a lambda inside it cannot yield.
API
class GeneratorClosed extends Exception
Thrown at a paused yield when its generator is dropped: the body unwinds.
Constructors
new GeneratorClosed()
class GeneratorState<T>
What a generator's body and its loop share.
Fields
value: Thas: bool = false //valueholds a value not yet taken—valueholds a value not yet takendone: bool = false // the body has finished— the body has finishedclosed: bool = false // the generator was dropped: stop at the next yield— the generator was dropped: stop at the next yieldfailure: Exception = nulltoLoop: Semaphore = new Semaphore(0) // a value (or the end) is ready— a value (or the end) is readytoBody: Semaphore = new Semaphore(0) // the loop wants the next one— the loop wants the next one
class Yielder<T>
The body's end of a generator: yield v is put(v).
Constructors
new Yielder(st: GeneratorState<T>)
Methods
fn put(v: T)— Handsvto the loop and waits until the loop asks for the next value.
class Generator<T> implements Iterator<T>
The values a body yields, as an Iterator.
Constructors
new Generator(body: fn(Yielder<T>))
Methods
fn hasNext() -> bool— Whether the body yields another value (running it up to that yield).fn next() -> T— The next value the body yields.