2.1 Iterators

A loop is typically intended to iterate over one or more quantities. This is realized by iterators expressed with the for macro.

<<for X = E1 while E2 'then' E3>>

This is very much like the C for(X=E1;E2;X=E3) loop. If while E2 is missing, it defaults to while
true
. If 'then' E3 is missing, X always keeps the same value, i. e. it defaults to 'then' X.

<<for X 'from' E1 to E2 by E3>>

This is very much like the C for(X=E1;X<=E2;X+=E3) loop but introduces appropriate local variables for E2 and E3 so that they are only computed once. If to E2 is missing, there is no upper limit. If by E3 is missing, it defaults to by 1. If 'from' E1 is missing, it defaults to 'from' 1. E3 should always be positive.

It is also permitted to use downfrom E1 and/or downto E2 to indicate counting downwards. However, E3 should still be positive.

<<for X 'in' L>>

Iterates over the elements of L.

An iterator may be introduced anywhere within the scope of the loop macro. The semantics is always identical: it declares an iterator globally for this loop. More than one iterator may be specified: the loop terminates as soon as one iterator terminates. For example:

loop
   <<for X 'in' [a b c d e]>> 
   <<for I 'from' 1 to 3>> 
   {Show I#X}
end

prints out:

1#a
2#b
3#c

Note that for esthetic reasons you may like to separate the section declaring the iterators from that of the body:

loop
   <<for X 'in' [a b c d e]>> 
   <<for I 'from' 1 to 3>> 
in 
   {Show I#X}
end

This is possible because the syntactic occurrence of an iterator simply expands to skip. Thus, in the above, the local declarations simply contain two skip.


Denys Duchier
Version 1.4.0 (20100209)