-
Notifications
You must be signed in to change notification settings - Fork 24
Sequences
Sequences (or generators) are special functions that can return any number of results (even an infinite amount!) to the calling code. They are defined like functions but they do not support the expression syntax ((a, b) -> a + b
).
seq oneToTen() {
for (var i = 1; i <= 10; i++)
yield i;
}
Values can be returned from sequences with yield <value>
. The sequence can be terminated with return
.
Sequences can be used with the [[foreach
loop|Loops#foreach]] or by manually calling the functions sequences define. The following are equivalent:
foreach (var i in oneToTen()) {
print(i);
}
var e = oneToTen().getEnumerator();
var i;
while (e.moveNext()) {
i = e.current;
print(i);
}
e.dispose();
Sequence operations can be combined by passing the result of one operation to another. Normally this would require expressions to be written like this:
toArray(where(range(0, 1000), x -> x % 5 == 0));
but that quickly turns messy. The pipeline operator (|>
) fixes this. It takes the expression on the left and inserts it into the function call on the right, meaning we can do this instead:
range(0, 1000) |> where(x -> x % 5 == 0) |> toArray();