11.03.2015 Views

Unicon Book

Unicon Book

Unicon Book

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

1.5. STRINGS AND CSETS 15<br />

local i, j, old_r, r<br />

i := read()<br />

j := read()<br />

old_r := r := min(i, j)<br />

while r > 0 do {<br />

old_r := r<br />

if i > j then<br />

i := r := i % j<br />

else<br />

j := r := j % i<br />

}<br />

write(old_r)<br />

end<br />

This example illustrates assignment; values are assigned to (or ”stored in”) variables<br />

with the := operator. As you saw in the previous section, the function read() reads a line<br />

from the input and returns its value. The modulo operator (%) is an important part of<br />

this program: i % j is the remainder when i is divided by j.<br />

While loops can use a reserved word do followed by an expression (often a compound<br />

expression in curly braces). The expression following the do is executed once each time the<br />

expression that controls the while succeeds. Inside the while loop, a conditional if-then-else<br />

expression is used to select from two possible actions.<br />

The names of the variables in this example are obscure, and there are no comments in<br />

it other than the one at the top. Can you guess what this program does, without running<br />

it? If you give up, try running it with a few pairs of positive numbers.<br />

In addition to arithmetic operators, there are augmented assignment operators. To<br />

increment the value in a variable by 2, these two statements are equivalent:<br />

i +:= 2<br />

i := i + 2<br />

Augmented assignment works for most binary operators, not just arithmetic. The expression<br />

i op:= expr means the same as i := i op expr.<br />

1.5 Strings and Csets<br />

The non-numeric atomic types in <strong>Unicon</strong> are character sequences (strings) and character<br />

sets (csets). Icon came from the domain of string processing, and from it <strong>Unicon</strong> inherits<br />

many sophisticated features for manipulating strings and performing pattern matching.<br />

This section presents the simple and most common operations. More advanced operations<br />

and examples using strings and csets are given in Chapter 4.

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

Saved successfully!

Ooh no, something went wrong!