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
factorialis a plaindefwith a plain runtime body.comptime ORDERINGS = factorial(SEATS)runs it during compilation.LABELshows that string building folds ahead of time too.
Keywords and builtins used here
IntStringdeffactorialformainprintrangereturnvar
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.
Step 4 of 5 in Compile-time Mojo, step 4 of 22 in Parameters & SIMD.