[Next] [Prev] [_____] [Left] [Up] [Index] [Root]
Iteration

Iteration

Enumerated sequences allow iteration over their elements. In particular, they can be used as the range set in the sequence and set constructors, and as domains in for loops.

When multiple range sequences are used, it is important to know in which order the range are iterated over; the rule is that the repeated iteration takes place as nested loops where the first range forms the innermost loop, etc. See the examples below.

for x in S do statements; end for;
An enumerated sequence S may be the range for the for-statement. The iteration only enumerates the defined terms of the sequence.

Example Seq_NestedIteration (H8E6)

The first example shows how repeated iteration inside a sequence constructor corresponds to nesting of loops.

> [<number, letter> : number in [1..5], letter in ["a", "b", "c"]];
[ <1, a>, <2, a>, <3, a>, <4, a>, <5, a>, <1, b>, <2, b>, <3, b>, <4, b>, <5, 
b>, <1, c>, <2, c>, <3, c>, <4, c>, <5, c> ]
> r := [];
> for letter in ["a", "b", "c"] do
>     for number in [1..5] do
>         Append( r, <number, letter>);
>     end for;
> end for;
> r;
[ <1, a>, <2, a>, <3, a>, <4, a>, <5, a>, <1, b>, <2, b>, <3, b>, <4, b>, <5, 
b>, <1, c>, <2, c>, <3, c>, <4, c>, <5, c> ]
This explains why the first construction below leads to an error, whereas the second leads to the desired sequence.


> // The following produces an error:
> print [ <x, y> : x in [0..5], y in [0..x] | x^2+y^2 lt 16 ]; ^ User error: Identifier 'x' has not been declared

> [ <x, y> : x in [0..y], y in [0..5] | x^2+y^2 lt 16 ]; [ <0, 0>, <0, 1>, <1, 1>, <0, 2>, <1, 2>, <2, 2>, <0, 3>, <1, 3>, <2, 3> ]

Note the following! In the last line below there are two different things with the name x. One is the (inner) loop variable, the other just an identifier with value 1000 that is used in the bound for the other (outer) loop variable y: the limited scope of the inner loop variable x makes it invisible to y, whence the error in the first case.


> // The following produces an error:
> print #[ <x, y> : x in [0..5], y in [0..x] | x^2+y^2 lt 100 ]; ^ User error: Identifier 'x' has not been declared

> x := 1000; > #[ <x, y> : x in [0..5], y in [0..x] | x^2+y^2 lt 100 ]; 59

[Next] [Prev] [_____] [Left] [Up] [Index] [Root]