module Loops {
import { /Std; }
// LOOP
// loop is an infinite loop, with support for break and continue
fn test1() {
let x = 0;
let sum = 0;
loop {
x += 1;
sum += x;
if (x % 10 == 0) {
continue;
}
if (x > 100) {
break;
}
print(x);
}
}
// WHILE
// while loops iterate while controlling expression is truthy
fn test2() {
let x = 0;
while (x < 10) { // loops while x is less than 10
x += 1;
if (x % 7 == 0) {
break;
}
}
}
// FOR
// for loops define a variable that iterates through
// values of an iterable value (a value that implements
// the Iterable interface). see iterators for more info
//
// the for variable is scoped to the for block/expression.
fn test3() {
// the val variable steps through the values of the array
for (val in [1, 2, 3, -1, 4]) {
if (val < 0) {
break;
}
print(val); // prints 1, 2, 3 (due to early break)
}
// a second "index" variable can be added which will contain the
// zero-based index of the loop. the type of the index variable is uint
for (val, index in ["a", "b"]) {
print(index, ":", val); // prints 0:a, 1:b
}
}
// LOOPS AS EXPRESSIONS
// for, loop and while can all be used as expressions
// • to produce a value from a loop, use break with an expression
// • if not all paths return a value, the value will be optional
fn test4() {
let a = [1, 2, 3, 4, -5, 6, 7];
// found will either be set to none if the value is not found
// or the index of the value if it is found.
let found = for(val, index in a) { // type of found is uint? (optional uint)
if (val < 0) {
break index; // break with index that value was found at
}
}
if (found != none) {
print("found! ", found!); // prints index (! obtains value of optional)
} else {
print("not found");
}
}
}