Control Flow
After introducing basic types and operations, it’s time to delve into more complex programs with control flow.
If-Else
An if-else expression allows you to branch based on a boolean value.
In contrast with some other languages, Roto does not require parentheses
around the condition, but it does require curly braces for the body. You
can use the if-else expression as a statement. The
else part is then optional.
fn main() {
let x = 100;
if x % 2 == 0 {
print("x is even");
} else {
print("x is odd");
}
}
x is even
An if-else expression can also evaluate to a value itself. That
value is determined by the last value in each of the arms, as long as there is
no semicolon at the end.
fn main() {
let x = 100;
let sign = if x > 0 {
print("x is positive");
1 // <- No semicolon!
} else {
print("x is negative");
-1 // <- No semicolon!
};
print(f"{sign}");
}
x is positive
1
It’s possible to declare variables within the arms of if-else
expressions, but they will only be available within that arm, and they will cease to exist on leaving that scope. The same goes
for any block of statements in Roto that is delimited by {}.
fn main() {
if true {
let x = 10;
print(f"{x}"); // This is fine!
}
print(f"{x}"); // This errors during type checking as x no longer exists here!
}
See also
if-else in the language reference
Match
@todo
While Loops
We can loop in Roto using a while loop. As in many other languages, a while loop takes a condition and then a block.
The body of the block is run repeatedly until the condition evaluates to false.
// Euclidean algorithm for greatest common divisor
fn main() {
let a_initial = 125;
let b_initial = 50;
let a = a_initial;
let b = b_initial;
while b != 0 {
let t = b;
b = a % b;
a = t;
}
print(f"gcd({a_initial}, {b_initial}) = {a}")
}
gcd(125, 50) = 25
See also
while in the language reference
For Loops
To execute some code for every element in a list, use
a for loop instead of a while loop.
fn main() {
for x in [10, 20, 30] {
let squared = x * x;
print(f"{x} squared is {squared}");
}
}
10 squared is 100
20 squared is 400
30 squared is 900
Note
A while loop is currently the best way to iterate over a range
of numbers. There will be support for using for loops with ranges
in the future. See this community post for more information.
See also
for in the language reference