Getting Started | Documentation | Glish | Learn More | Programming | Contact Us |
Version 1.9 Build 1556 |
|
Glish supports two looping constructs, while and for.
while ( expression ) statementwhere 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.
Glish supports a different style of for loop than C. A Glish for loop looks like:
for ( variable in expression ) statementWhen 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.
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.