Next: , Previous: , Up: Iterating   [Contents][Index]


Range loops

Range loops

Range loops are coNCePTuaL’s most powerful looping construct. Unlike the counted-loop construct presented in Counted loops, a range loop binds a variable to a different value on each iteration. Range loops have the following syntax:

FOR EACH <ident>
IN <range> [, <range>]*
<simple_stmt>

A <range> represents a range expression. Range expressions are described in Range expressions. In short, a range expression specifies a list of values by explicit enumeration, numeric progression, or predicated combinations of other range expressions. For a range loop, coNCePTuaL successively binds a specified variable to each <expr> in each <range> and evaluates the given <simple_stmt>.

The following are some examples of the FOR EACH statement from simplest to most elaborate. Each example uses ‘i’ as the loop variable and ‘TASK 0 OUTPUTS i’ as the loop body. The output from each example is shown with a “-|” symbol preceding each line.

FOR EACH i IN {8, 7, 5, 4, 5} TASK 0 OUTPUTS i
-| 8
-| 7
-| 5
-| 4
-| 5

FOR EACH i IN {1, ..., 5} TASK 0 OUTPUTS i
-| 1
-| 2
-| 3
-| 4
-| 5

FOR EACH i IN {5, ..., 1} TASK 0 OUTPUTS i
-| 5
-| 4
-| 3
-| 2
-| 1

FOR EACH i IN {1, ..., 5}, {8, 7, 5, 4, 5} TASK 0 OUTPUTS i
-| 1
-| 2
-| 3
-| 4
-| 5
-| 8
-| 7
-| 5
-| 4
-| 5

FOR EACH i IN {1, 4, 7, ..., 30} TASK 0 OUTPUTS i
-| 1
-| 4
-| 7
-| 10
-| 13
-| 16
-| 19
-| 22
-| 25
-| 28

FOR EACH i IN {3**1, 3**2, 3**3, ..., 3**7} TASK 0 OUTPUTS i
-| 3
-| 9
-| 27
-| 81
-| 243
-| 729
-| 2187

FOR EACH i IN {0}, {1, 2, 4, ..., 256} TASK 0 OUTPUTS i
-| 0
-| 1
-| 2
-| 4
-| 8
-| 16
-| 32
-| 64
-| 128
-| 256

FOR EACH i IN {neigh FOR EACH neigh IN {0,...,100} WHERE
MESH_DISTANCE((10,10), 55, neigh) IS IN {1, 2}} TASK 0 OUTPUTS i.
-| 35
-| 44
-| 45
-| 46
-| 53
-| 54
-| 56
-| 57
-| 64
-| 65
-| 66
-| 75

That final example loops over all values that are a Manhattan distance of either 1 or 2 from the number 55 in a 10x10 layout of the numbers 0–99.

FOR EACH loops with constant progressions are executed exactly once. Note that if the <range> does not contain an ellipsis then all values are used, regardless of order or constancy:

FOR EACH i IN {4, 4, 4, ..., 4} TASK 0 OUTPUTS i
-| 4

FOR EACH i IN {4, 4, 4, 4, 4} TASK 0 OUTPUTS i
-| 4
-| 4
-| 4
-| 4
-| 4

Next: , Previous: , Up: Iterating   [Contents][Index]

Scott Pakin, pakin@lanl.gov