Yielding

A return statement ends the execution of a program and determines its result. Sometimes, however, it is convenient to have a program emit sequence of results, one by one. This is known as yielding.

yield

In a script step, or in the body of a function, you can use the yield statement to emit a result. Unlike a return statement, a yield statement does not end the program. Instead, program execution continues.

A program or function which contains yield statements will, when finished, return a sequence of all its yielded values.

// Example 1: A program which yields some values.

yield 1;
yield 2;
yield 3;

// Result will be the sequence value [1, 2, 3]

Yielding is often used in with for-loops to create sequence from some other sequence.

// Example 2: A program which yields from inside a loop

for x in [1, 2, 3] {
    yield x * 2;
}

// Result will be [2, 4, 6];

yield from

In a program which yields, you can use the yield from construct to yield several values at once.

Advanced: Lazy evaluation

A function which yields its values is lazily evaluated: the sequence of elements emitted by the function is computed on-demand whenever needed. This means that you can, for example, create infinite sequences. It also means that yielding functions may appear to be re-executed unexpectedly .

Last updated

Was this helpful?