11.03.2015 Views

Unicon Book

Unicon Book

Unicon Book

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

1.9. ITERATION AND CONTROL STRUCTURES 21<br />

every write(1 to 10)<br />

A generator operand to a non-generator forms a generator. The enclosing non-generator<br />

(such as write()) is re-run each time the generator suspends and resumes.<br />

<strong>Unicon</strong>’s every keyword generalizes the concept of iterators found in other languages.<br />

Iterators are special control structures that walk through a collection of data. Instead of<br />

being a special feature, in <strong>Unicon</strong> iterators are just one of many ways to utilize generators.<br />

The sequence of results from an expression does not have to be stored in a structure to<br />

iterate over them. The sequence of results does not even have to be finite; many generator<br />

expressions produce an infinite sequence of results, as long as the surrounding expression<br />

keeps asking them for more. Here is another example of how every expressions are more<br />

flexible than for loops. The expression<br />

every f(1 | 4 | 9 | 16 | 25 | 36)<br />

executes the function f several times, passing the first few square numbers as parameters.<br />

A shorter equivalent that uses the power operator (ˆ) is every f((1 to 6)ˆ2). An example in<br />

the next section shows how to generalize this to work with all the squares.<br />

The if, while, and every expressions are <strong>Unicon</strong>’s primary control structures. Several<br />

other control structures are available that may be more useful in certain situations. The<br />

loop<br />

until expr1 do expr2<br />

is while’s evil twin, executing expr2 as long as expr1 fails; on the other hand<br />

repeat expr<br />

is an infinite loop, executing expr over and over.<br />

There are also variations on the if expression introduced earlier for conditional execution.<br />

First, the else branch is optional, so you can have an if expression that does nothing if<br />

the condition is not satisfied. Second, there is a special control structure introduced for<br />

the common situation in which several alternatives might be selected using a long sequence<br />

of if ... else if ... else if ... expressions. The case expression replaces these chains of if<br />

expressions with the syntax:<br />

case expr of {<br />

branch1: expr1<br />

branch2: expr2<br />

...<br />

default: expr i<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!