Conditionals and Loops
def a = 5;
if (a > 0) then assert(true);
if (a > 0) assert(true); // then is optional
if (a > 0) assert(true) else assert(false);
var b;
if (a > 0) { // with block (curly braces)
b = 1;
}
else {
b = -1;
}
assert(b == 1);
var c = if (b == 1) "foo" else "bar"; // if/else returns value
def d = if (b == 1) {
println("b is 1.");
"foo"; // last expression in block will be returned
}
else {
println("b is not 1;");
"bar";
};
assert(d == "foo");
var sum = 0;
for (i in [1..4]) // iterates through a sequence
sum += i;
assert(sum == 10);
def a = for (i in [1..3]) i * i; // returns a new sequence
assert(a == [1, 4, 9]);
def b = for (i in [1..7] where i mod 2 != 0) i * i; // restricts sequence
assert(b == [1, 9, 25, 49]);
def c = for (i in [5..7], j in [1..3]) i - j; // two sequences in one loop (more)
assert(c == [4, 3, 2, 5, 4, 3, 6, 5, 4]);
def d = for (i in [1..5] where i mod 2 != 0, j in [1..5] where i <= j) i * j;
assert(d == [1, 2, 3, 4, 5, 9, 12, 15, 25]);
var i = 0;
for (i in [1..5]) // creates new variable named i
sum += i;
assert(i == 0); // i did not change
var a = 0; var b = 3;
while (b > 0) // repeats a block while condition is true
a = a + (b--);
assert(a == 6);
def b = while (a > 0) a--; // while returns Void
var a = ""; var b = ["abc", "d", "efg", "hij", "k", "lmnop", "qrs"];
for (i in b) {
a = "{a}{i}";
if (a.length() >= 10)
break; // aborts the loop
}
assert(a == "abcdefghij");
var c = 0; var d = 0;
while (c <= 10) {
d += c * c;
if (d > 100)
break; // aborts the loop
c++;
}
assert(d == 140);
var a = ""; var b = ["abc", "d", "efg", "hij", "k", "lmnop", "qrs"];
for (i in b) {
if (a.length() >= 10)
continue; // skips the rest of the current iteration
a = "{a}{i}";
}
assert(a == "abcdefghij");
var c = 0; var d = 0;
while (c <= 10) {
c++;
if (d > 100)
continue; // skips the rest of the current iteration
d += c * c;
}
assert(d == 140);

