For Loop Expressions

From The Oxygene Language Wiki
Jump to: navigation, search

This is a Language topic about Oxygene
 

Language Topics Introduction | Structured Overview | Grammar | Keywords | Functions


For expressions are a way to do loops as part of an expression, symmetrical to the new case expressions.


For loop

For loop expressions are a simple way to use the Pascal for i := start to end (optional step) syntax to create a sequence. All features supported by the Oxygene for loops are supported by the loop expression except that "do" is replaced with "yield":

var
  lList := for i := 0 to 10 step 2 yield i*i; // returns 0, 4, 16, 36, 64, 100

For each loop

Like for expressions, for each can work with any statement and can provide access to the index of an element in the source list. For each loops are convenient to turn one sequence into another.

var
  lOriginalList: array of Integer := [0,1,2,3,4,5,6,7,8,9];
  lList := for each el in lOriginalList index n yield el * n; // returns: 0, 1, 4, 9, 16, 25, 36, 49, 64, 81

Details

The result of both are a sequence of the type of the yield expression. Items are not pre-evaluated but will be looped through whenever the caller calls the IEnumerator<T>.MoveNext call (which is called every iteration of a regular for each loop). Note that the type of both loops is determined by the result type of the yield expression, which can be anything. For example:

var
  lList := for i := 0 to 10 step 2 yield (i*i).ToString; 
  // returns a sequence of string; '0', '4', '16', '36', '64', '100'


See Also

Personal tools
Namespaces

Variants
Actions
Navigation
Getting Started
Sections
If you know
More
Toolbox