Example 8-6. Example:
break! |
break!_expression ==>
break! |
break! expressions are iterator calls which immediately quit when they are called.
Example 8-7. Because they are so useful, the 'while!', 'until!' and 'break!' iterators are built into the language. Here's how 'while!' could be written if it were not a primitive.
while!(pred:BOOL) is -- Yields as long as 'pred' is true loop if pred then yield else quit end end end |
Example 8-8. The built-in class 'INT' defines some useful iterators. Here's the definition of 'upto!'. Unlike the argument 'pred' used above, 'i' here is declared to be 'once'; when 'upto!' is called, the argument is only evaluated once, the first time the iterator is called in the loop.
upto!(once i:SAME):SAME is -- Yield successive integers from -- self to 'i' inclusive. r::=self; loop until!(r>i); yield r; r:=r+1 end end; |
Example 8-9. To add up the integers 1 through 10, one might say:
x::=0; loop x:=x+1.upto!(10) end |
Example 8-10. Or, using the library iterator 'sum!' like this. 'x' needs to be declared (but not initialized) outside the loop.
loop x:=INT::sum!(1.upto!(10)) end |
Example 8-11. Some of the most useful ways to use iters is with container objects. Arrays, lists, sets, trees, strings, and vectors can all be given iterators to yield all their elements. Here we print all the elements of some container 'c'.
loop #OUT + c.elt!.str + '\n' end |
Example 8-12. This doubles the elements of array 'a'.
loop a.set!(a.elt! * 2) end |
Example 8-13. This computes the dot product of two vectors 'a' and 'b'. There is also a built-in method 'dot' to do this. 'x' needs to be declared (but not initialized) before the loop.
loop x:=sum!(a.elt! * b.elt!) end |