typestar

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

  1. scaled[factor: Int] bakes the multiplier into each specialization.
  2. scaled[3](7) and scaled[10](7) compile to two separate functions.
  3. repeated[times] shows a parameter driving a loop bound.

Keywords and builtins used here

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.

Type this snippet

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

← Previous Next →