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
describe[width]chooses on a parameter, so only onereturnsurvives.comptime forunrolls the countdown into three separateprintcalls.- Both spellings replace the deprecated
@parameterdecorator.
Keywords and builtins used here
IntStringcountdowndefdescribeelseforifmainprintrangereturn
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.
Step 5 of 5 in Compile-time Mojo, step 5 of 22 in Parameters & SIMD.