Skip to content

Control Flow

Control Structures in Helix

Control flow in Helix combines familiar constructs with expressive syntax and modern additions like pattern matching.

Helix currently supports:

  • if-else
  • while loops
  • for loops
  • match expressions (pattern matching similar to switch)
  • break and continue
  • return

If / Else

The if expression allows conditional execution of code blocks.

A simple if statement looks like this:

if x > 0 {
print(x);
}

if blocks can be stacked in order to make a decision tree, using the else keyword like this:

let score = 85;
if score > 90 {
print("Excellent");
} else if (score > 75) { //as noted earlier, condition brackets are optional
print("Good");
} else {
print("Keep trying");
}

While

The while expression can be used to loop through statements while a given condition(s) returns true.

A simple while loop looks like this:

let x = 0;
while x < 3 {
print(x);
x++;
}

For

for loops essentially let you iterate over a range

A simple helix for loop looks like this:

for var i:i32 = 0; i < 100; i++ {
print(i);
}

Additionally, even here, you could use traditional condition brackets, like:

for (var i:i32 = 0; i < 100; i++){
print(i);
}

Multiple initializations or increments can be done at once using a comma , (multiple conditions are achieved by using logical operators like && or ||) :

for (var i:i32 = 0, var j:i32 = 3; i < 100; i++, j--){
print(i)
}

If you are looping over any array, string, map, or any compatible list-like structure, helix has a range clause:

for letter in word {
print(word[letter]);
}

Match

Due to match having a lot of extra features on it, we made a completely separate page for it. To learn more, refer to the Match Guide

Break/continue

break and continue in helix serve the same purpose they do in other languages.

break is used to exit a loop

let count = 0;
for letter in sentence{
if letter == ' ' {
break; //breaks the loop after the first word in the sentence is iterated over
}
count++;
}
print(count); //prints the length of the first word

continue skips the current iteration and moves to the next one.

let count = 0;
for letter in sentence {
if letter == ' ' {
continue; //skips spaces and continues with the next character
}
count++;
}
print(count); //prints the length of the sentence excluding whitespaces

Return

return is used to exit a function and pass a value back to the caller of the function

fn square(x:i32) -> i32 {
return x * x;
}
let result = square(5);
print(result);

References