2.17 For

for simple-var in list-expr do statements od;

The for loop executes the statement sequence statements for every element of the list list-expr.

The statement sequence statements is first executed with simple-var bound to the first element of the list list, then with simple-var bound to the second element of list and so on. simple-var must be a simple variable, it must not be a list element selection list-var[int-expr] or a record component selection record-var.ident.

The execution of the for loop is exactly equivalent to the while loop

loop-list := list

;
    
loop-index
 := 1;
    while 
loop-index <= Length(loop-list
) do
        
variable := loop-list[loop-index
];
        
statements
        
loop-index := loop-index
 + 1;
    od; 

with the exception that loop-list and loop-index are different variables for each for loop that do not interfere with each other.

The list list is very often a range.
for variable in [from..to] do statements od;
corresponds to the more common
for variable from from to to do statements od;
in other programming languages.

    gap> s := 0;;
    gap> for i  in [1..100]  do
    >        s := s + i;
    > od;
    gap> s;
    5050 

Note in the following example how the modification of the list in the loop body causes the loop body also to be executed for the new values

    gap> l := [ 1, 2, 3, 4, 5, 6 ];;
    gap> for i  in l  do
    >        Print( i, " " );
    >        if i mod 2 = 0  then Add( l, 3 * i / 2 );  fi;
    > od;  Print( "\n" );
    1 2 3 4 5 6 3 6 9 9
    gap> l;
    [ 1, 2, 3, 4, 5, 6, 3, 6, 9, 9 ] 

Note in the following example that the modification of the variable that holds the list has no influence on the loop

    gap> l := [ 1, 2, 3, 4, 5, 6 ];;
    gap> for i  in l  do
    >        Print( i, " " );
    >        l := [];
    > od;  Print( "\n" );
    1 2 3 4 5 6
    gap> l;
    [  ] 

Previous Up Top Next
Index

GAP 3.4.4
April 1997