Parametric functions in Mojo
Square brackets take compile-time parameters; parentheses take runtime arguments.
def scaled[factor: Int](value: Int) -> Int:
return value * factor
def repeated[times: Int](text: String) -> String:
var out = String()
for _ in range(times):
out += text
return out
def main():
print(scaled[3](7), scaled[10](7))
print(repeated[3]("ha"))
How it works
scaled[factor: Int]bakes the multiplier into each specialization.scaled[3](7)andscaled[10](7)compile to two separate functions.repeated[times]shows a parameter driving a loop bound.
Keywords and builtins used here
IntStringdefformainprintrangerepeatedreturnscaledvar
The run, in numbers
- Lines
- 14
- Characters to type
- 256
- Tokens
- 79
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 68 seconds.
Step 2 of 5 in Compile-time Mojo, step 2 of 22 in Parameters & SIMD.