typestar

Compile-time branching in Mojo

comptime if and comptime for are resolved by the compiler, leaving no branch behind.

def describe[width: Int]() -> String:
    comptime if width >= 8:
        return "wide"
    else:
        return "narrow"


def countdown[start: Int]():
    comptime for i in range(start, 0, -1):
        print(i)


def main():
    print(describe[16](), describe[4]())
    countdown[3]()

How it works

  1. describe[width] chooses on a parameter, so only one return survives.
  2. comptime for unrolls the countdown into three separate print calls.
  3. Both spellings replace the deprecated @parameter decorator.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
242
Tokens
69
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 64 seconds.

Type this snippet

Step 5 of 5 in Compile-time Mojo, step 5 of 22 in Parameters & SIMD.

← Previous Next →