next up previous contents index
Next: return Statement Up: Statements Previous: Conditionals


  Glish supports two looping constructs, while and for.

While Loops

  A while loop looks like:

while ( expression ) statement
As in C, upon encountering a while statement the expression is evaluated (in the same way as in an if statement; see § 5.4, page gif) and statement executed if true. expression is then evaluated again and if true the process repeats.

For Loops


  Glish supports a different style of for loop than C provides. A Glish for loop looks like:

for ( variable in expression ) statement
When the for is executed, expression is evaluated to produce a vector value. variable is then assigned to each of the values in the vector in turn, beginning with the first and continuing to the last. For each assignment, statement is executed. Upon exit from the loop variable keeps the last value assigned to it.

  Here, for example, is a for loop that prints the numbers from 1 to 10 one at a time:

    for ( n in 1:10 )
        print n

Here's another example, this time looping over all the even elements of the vector x:

    for ( even in x[x % 2 == 0] )
        print even

Here's a related example that loops over the indices of the even elements of x:

    for ( even in seq(x)[x % 2 == 0] )
        print "Element", even, "is even:", x[even]

And one final example, looping over each of the fields in a record r:

    for ( f in field_names(r) )
        print "The", f, "field of r =", r[f]

  The philosophy behind providing only this style of for loop is rooted in the fact that Glish is most efficient when doing operations on vectors. I believe that this for loop (which was taken from the S language) encourages the programmer to think about problems in terms of vectors, while C's for loop does not.

Controlling Loop Execution

  Glish provides two ways to control the execution of a loop, the next  and break  statements, which are directly analogous to C's continue and break (indeed,   continue is allowed as a synonym for next). The syntax of these is simply:



next ends the current iteration of the surrounding while or for loop and begins the next iteration, or exits the loop if there are no more iterations. break immediately exits the loop regardless of whether there normally would be more iterations.    

next up previous contents index
Next: return Statement Up: Statements Previous: Conditionals

Thu Nov 13 16:44:05 EST 1997