typestar

Span views in Mojo

A Span borrows a window into a list without copying any of it.

def total(values: Span[Int, _]) -> Int:
    var sum = 0
    for value in values:
        sum += value
    return sum


def main():
    var samples = [3, 1, 4, 1, 5, 9, 2, 6]
    print(total(Span(samples)))
    print(total(Span(samples)[2:5]))
    var window = Span(samples)[0:3]
    window[0] = 100
    print(samples[0])

How it works

  1. Span[Int, _] leaves the origin unbound, so any list can be passed.
  2. Slicing a span narrows the window to a sub-range.
  3. Writing through the span mutates the original list.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
276
Tokens
96
Three-star pace
70 tpm

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

Type this snippet

Step 4 of 4 in Memory, step 20 of 22 in Parameters & SIMD.

← Previous Next →