For Loop Expressions

For Loop Expressions are a way to use a regular for Loop as part of an expression, symmetrical to the new Case Expressions and If Expressions. The result of the for loop expression is a Sequence of values (implemented internally the same way as an Iterator would be).

Just as the regular for Loop Statement, the for loop expression supports for/to loops that iterate over a range of numbers, and for each loops that can iterate over an existing sequence.

Because for loop expressions generate a sequence, rather than performing a repeated action, they use the yield keyword, instead of do, to provide the expression for each iteration:

var lSquares := for i: Integer := 0 to 9 yield i**2; 

The result of the above expression is a sequence that, when iterated, will contain the numbers 0, 1, 4, 9, 16, 25, 36, 49, 64, 81...

Note that, just like Iterators, the for expression does not actually run the full sequence and generate all values ahead of time. It merely defines how each ite of the sequence will be generated. It is not until the sequence is iterated, for example with a for each loop statement, or a LINQ function sich as .ToList().

Also just as the regular for Loop Statements, downto can be used to count downwards instead of up, step can be used to change the increment for each loop iteration, index and provide a separate index counter and matching can filter a for each loop down to a specific set of subtypes.

breaking out of a for loop statement or continueing an iteration without value is not supported, but it is allowed for an iteration to raise an Exception via a raise Expression.

See Also