Getting Started Documentation Glish Learn More Programming Contact Us
Version 1.9 Build 1556
News FAQ
Search Home


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

Subsections


Loops

Glish supports two looping constructs, while and for.

While Loops

A while loop looks like:

while ( expression ) statement
where statement can be a statement block (enclosed in braces) or a single statement. As in C, when encountering a while statement the expression is evaluated in the same way as in an if statement. (See § 5.4, page [*]). If true, statement is executed and expression is then evaluated again and if true the process repeats.


For Loops

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

for ( variable in expression ) statement
When the for is executed, expression is evaluated to produce a vector value. Then variable is assigned to each of the values in the vector, 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 performing 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

break

The next statement 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. The break statement immediately exits the loop regardless of whether or not there are normally more iterations.


next up previous contents index
Next: return Statement Up: Statements Previous: Conditionals   Contents   Index
Please send questions or comments about AIPS++ to aips2-request@nrao.edu.
Copyright © 1995-2000 Associated Universities Inc., Washington, D.C.

Return to AIPS++ Home Page
2006-10-15