next | previous | forward | backward | up | top | index | toc | Macaulay2 web site
Macaulay2Doc > The Macaulay2 language > for

for -- for loops

Synopsis

Description

Synopsis

  • Usage:
    for i in v when p list x do z
  • Inputs:
  • Consequences:
    • The variable i is set to consecutive values of the list v. First p is evaluated. As long as the value of p is true, evaluation of the loop continues. Next x is evaluated, and its value is saved. Then z is evaluated and its value is discarded. Then the loop repeats with the next element of v. When the value of p is false, then the loop terminates, and the list of values of x is returned as the value of the entire expression.

examples

i1 : for i from 1 to 5 when i < 15 list i^2 do print i
1
2
3
4
5

o1 = {1, 4, 9, 16, 25}

o1 : List
i2 : for i from 1 to 5 when i^2 < 15 list i^2 do print i
1
2
3

o2 = {1, 4, 9}

o2 : List

The do z clause may be omitted.

i3 : for i from 1 to 5 when i < 15 list i^2

o3 = {1, 4, 9, 16, 25}

o3 : List

The from m clause may be omitted, in which case i starts with 0.

i4 : for i to 5 when i < 15 list i^2

o4 = {0, 1, 4, 9, 16, 25}

o4 : List

The when p clause may be omitted.

i5 : for i to 5 list i^2

o5 = {0, 1, 4, 9, 16, 25}

o5 : List

The to n clause may be omitted.

i6 : for i when i < 15 list i^2

o6 = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196}

o6 : List

The list x clause may be omitted.

i7 : for i when i^2 < 15 do print i
0
1
2
3

If continue is executed by x then execution of x is interrupted, no value is added to the list, and iteration of the loop continues.

i8 : for i from 0 when i < 10 list (if odd i then continue; i^2)

o8 = {0, 4, 16, 36, 64}

o8 : List

If continue w is executed by x then execution of x is interrupted, the value of w is added to the list, and iteration of the loop continues.

i9 : for i from 0 when i < 10 list (if odd i then continue 4567; i^2)

o9 = {0, 4567, 4, 4567, 16, 4567, 36, 4567, 64, 4567}

o9 : List

If break v is executed by x, then the loop is stopped and v is returned as its value.

i10 : for i from 0 when i < 10 list (if i== 5 then break i; i^2)

o10 = 5

If break is executed by x, then the loop is stopped and the list accumulated so far is returned as the value.

i11 : for i from 0 when i < 10 list (if i== 5 then break; i^2)

o11 = {0, 1, 4, 9, 16}

o11 : List
i12 : for i in 0..3 list i^2

o12 = {0, 1, 4, 9}

o12 : List

Caveat

The variable i is a new local variable whose scope includes only the expressions p, x, and y in the body of the loop; moreover, new local variables defined inside the body of the loop will not be visible outside it. The numbers m and n must be small integers that fit into a single word.

For the programmer

The object for is a keyword.