Control Flow
If and Else
⚠️ TODO
Example
if (x > 12) {
if (x > 20)
print("number is larger than 20");
} else {
print("is smaller or equal to 12");
}
Unconditional Loop
An unconditional loop can be written with the loop keyword.
Example
loop {
if (cond())
break;
print("looping...");
}
The following statements can be used to control the control flow of the loop:
break;: Jumps out of the loop scope and continues execution at the statement following theloopcontinue: Jumps to the start of the loop scope, skipping the rest of the statements within the loop scope
In addition to these, return, throw and the ! operator can also cause the
loop to be terminated.
C-Style For Loop
The first form of the for loop behaves very similar to C/C++ in terms of
semantics and syntax. It consists of three optional parts, separated by
semicolons:
- The first part contains a list of declarations for variables that will be visible inside the loop scope.
- The second part is a condition that must evaluate to true in order for the
loop to keep iterating. Omitting it is equivalent to using
trueas the condition. - The third part is a list of expressions that will be evaluated after each
loop iteration, including after using
continueto force starting a new iteration.
Example
for (i: int = 0; i < 12; i++)
print(i);
// the loop variable type can be inferred
for (i = 0; i < 12; i++)
print(i);
// multiple variable declarations and increment
// expressions can be separated by commas
for (i = 0, j = 1; i * j < 12; i++, j++)
print("$(i) × $(j) = $(i * j)");
// any part can be left off
var i = 0;
for (; i < 12;) {
print(i);
i++;
}
// equivalent to `loop {}`
var i = 0;
for (;;) {
if (i >= 12)
break;
print(i);
i++;
}
Range Based For Loop
The second for of the for loop operates on
Example
// loops over all integers from 0 to 9
for (i; 0 .. 10)
print(i);
// loops over the integers 2, 5 and 8
for (n; [2, 5, 8])
print(n);
// any input range can be iterated, a lazy
// range of even numbers from zero to 18 in
// this case
for (n; (0 .. 10).map(i => 2 * i))
print(n);
// two loop variables can be declared, in
// which case the first variable will contain
// index of the loop iteration/range element
for (i, n; (0 .. 10).map(i => 2 * i))
print("$(i+1). number: $(n)");
Switch Statement
Switch statements allow to branch code execution based on the value of an
expression. Each case statement nested within the switch can match one
or more possible values or ranges of values. Any value not matched by a case
statement will be matched by the default statement.
A switch statement must handle all possible values of the input expression,
either by explicitly matching all possible values, or by using a default
statement. Each possible input value must match exactly one case or default
statement.
⚠️ TODO
Example
switch (x) {
case 0: print("zero");
case 1: print("one");
default: print("other");
}
enum E { a, b, c }
var e: E;
switch (e) {
case E.a: print("A");
case E.b: print("B");
case E.c: print("C");
}