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

The for statement

The for-statement is one of Magma's iterative statements. It has the syntax:

for IDENTIFIER in DOMAIN do
    STATEMENT;
    ...
    STATEMENT;
end for;

To execute this statement, Magma assigns each element of the domain in succession to the identifier, and the statements enclosed between `do' and `end for' are executed for each of these values.

The domain must be a finite enumerated structure, that is, a structure all of whose elements Magma can assign to the identifier one by one. If the domain is one whose elements have a fixed order, such as a sequence, then the elements will be assigned to the identifier in that order. If the domain is empty then the statements within the loop are never executed.

If you are entering a for-statement into Magma interactively, you will normally be given a special prompt

for>

until you type end for; .

The identifier of a for-statement is of the value class of identifiers. Therefore it cannot be reassigned within the loop, and its scope is local to the loop.

The for-statement

for IDENTIFIER := B to E by S do
    STATEMENT;
    ...
    STATEMENT;
end for;

where B, E and S are integer-valued expressions, is equivalent to the one beginning for IDENTIFIER in [B..E by S] do See Sequences for an explanation of the sequence constructor [B..E by S].

Many short for-statements can also be encoded using set or sequence constructors, with associated operations such as sequence reduction and quantifier tests.

The statement break; within a for-loop causes the loop to stop immediately. Execution proceeds from the statement immediately after the loop.

The statement continue; within a for-loop causes Magma to omit the rest of the block of statements and go on to the next element of the domain.

In a for-statement nested inside another for-statement, the statement

> break IDENTIFIER;

causes an exit from the for-loop whose loop identifier is the given identifier. This allows an exit from a loop other than the innermost one. The behaviour of

> continue IDENTIFIER;

is analogous.

Example

> for g in Sym(3) do 
for> print g;
for> end for;
Id($)
(1, 2, 3)
(1, 3, 2)
(2, 3)
(1, 2)
(1, 3)

> // product of the composite numbers from 2 to 50
> product := 1;
> for i := 2 to 50 do
for> if IsPrime(i) then
for|if> continue;
for|if> end if; 
for> product *:= i;
for> end for;
> print product;
49462674552307032732500869107626803200000000000

> p := 10037;
> for x in [1..100] do
for> for y in [1..100] do
for|for> if x^2 + y^2 eq p then
for|for|if> print x, y;
for|for|if> break x;
for|for|if> end if;
for|for> end for;
for> end for;
46 89

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