typestar

Compile-time expressions in Mojo

An ordinary function runs at compile time when its result feeds a comptime binding.

def factorial(n: Int) -> Int:
    var result = 1
    for i in range(2, n + 1):
        result *= i
    return result


comptime SEATS = 5
comptime ORDERINGS = factorial(SEATS)
comptime LABEL = "orderings: " + String(ORDERINGS)


def main():
    print(SEATS, ORDERINGS)
    print(LABEL)

How it works

  1. factorial is a plain def with a plain runtime body.
  2. comptime ORDERINGS = factorial(SEATS) runs it during compilation.
  3. LABEL shows that string building folds ahead of time too.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
257
Tokens
67
Three-star pace
70 tpm

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

Type this snippet

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

← Previous Next →