Docs / Language

Control flow

Use typed if branches and bounded range, streaming file, and while loops in Zhex.

Browse documentation
On this page

if selects a branch, and for and while repeat a block. Each block has lexical scope. Conditions, branch results, and loop bounds are checked before the program runs.

Choose with if

Conditions must have type Bool. Add any number of elif branches and an optional else:

word fizzbuzz(n: Int) -> String
    if n % 15 == 0
        "FizzBuzz"
    elif n % 3 == 0
        "Fizz"
    elif n % 5 == 0
        "Buzz"
    else
        int.to-string(n)

When an if is used as a value, its branches must return the same type. Without else, the missing branch supplies Unit, so every present branch must also return Unit; a value-producing if needs an else. Each branch has its own scope.

Repeat a range

range(start, end) iterates upward from start and stops before end. Both bounds are evaluated once. If start >= end, the loop body does not run. The iteration name is an immutable Int, local to the loop.

var total = 0
for n in range(1, 5)
    total = total + n
print(total)

This prints 10. The loop itself has type Unit; it does not produce a collection or a final value. range is available only in this loop syntax.

Stream a file’s lines

The other built-in loop forms are for line in file.stream(path) and collection iteration. The file form reads one UTF-8 line at a time and binds each chomped line as an immutable String:

for line in file.stream("examples/text-stats-sample.txt")
    print(text.upper(line))

Run that program from the repository root so the sample path resolves.

The loop closes the file when it finishes, including when the body fails. An empty file runs no iterations. A final line without a newline still runs. See files for line ending and failure details.

Lists and arrays can also be traversed with for value in collection; see collection iteration for index and coordinate bindings, traversal order, and mutation rules.

Repeat while a condition holds

while condition repeats an indented body for as long as its condition holds. The condition must have type Bool and is evaluated before each pass, so a false condition runs no passes. A var updated in the body drives termination:

var n = 1
while n <= 4
    print(n)
    n = n + 1

This prints 1 through 4. The loop is a statement of type Unit; it cannot be the right-hand side of a binding or assignment. There is no break or continue — change the condition, or the values it reads, to leave the loop. A while may run forever by design: there is no iteration limit, and the word-call depth limit does not apply to iterations.

Loops and branches can contain calls and flows. See words and flows and values for the related type and scope rules.