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.
// Example 3: A function which adds an element to the beginning of a sequence
// (equivalent to the built-in Seq.prepend function):
function addFirst<T>(self xs: T*, x: T) {
yield x;
yield from xs;
}
return [1, 2].addFirst(0); // returns [0, 1, 2]
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 .
open Seq;
// Example: Using an infinite list of dates to easily calculate the next Friday.
function infiniteDaysFrom(d: datetime) {
let n = 0;
while true {
yield DateTime.addDays(d, n);
set n = n + 1;
}
}
function nextFriday() =>
infiniteDaysFrom(now())
.skipWhile(d => DateTime.getDayOfWeek(d) != "friday")
.first();
return nextFriday();
Last updated
Was this helpful?