Generics

// [T] after a function's name makes it generic: T stands for any type
fn first[T](xs: list[T]) -> T:
    ret xs[0]

print(first([3, 1, 2]))
print(first(["a", "b"]))

// a generic function can have several type parameters
fn swap[A, B](pair: tuple[A, B]) -> tuple[B, A]:
    a, b = pair
    ret (b, a)

print(swap((1, "one")))

// T can be held in lists, tuples, and options, and moved around
fn repeat[T](x: T, n: int) -> list[T]:
    out = []
    for _ in range(n):
        out.append(x)
    ret out

fn or_else[T](x: option[T], fallback: T) -> T:
    match x:
        case some(value):
            ret value
        case none:
            ret fallback

print(repeat("ab", 3))
print(or_else(some(1.5), 0.0), or_else(none, "nothing"))

// structs and enums can be generic too, and a value fills in their types
struct Pair[A, B]:
    first: A
    second: B

impl Pair:
    fn swap(self) -> Pair[B, A]:
        ret Pair(first=self.second, second=self.first)

enum Tree[T]:
    Leaf
    Node(Tree[T], T, Tree[T])

fn count[T](t: Tree[T]) -> int:
    match t:
        case Tree.Leaf:
            ret 0
        case Tree.Node(left, _, right):
            ret count(left) + 1 + count(right)

p = Pair(first=1, second="one")
print(p, p.swap(), p.first + 1)
t = Tree.Node(Tree.Leaf, "a", Tree.Node(Tree.Leaf, "b", Tree.Leaf))
print(count(t), count(Tree.Node(Tree.Leaf, 2.5, Tree.Leaf)))

prints

3
a
('one', 1)
['ab', 'ab', 'ab']
1.5 nothing
Pair(first=1, second='one') Pair(first='one', second=1) 2
2 1

Type parameters

A function that works the same way on values of any type is written once, with type parameters in brackets after its name: fn first[T](xs: list[T]) -> T: takes a list of any type and returns a value of that type. Inside the signature, T is used like any other type, alone or inside list[T], tuple[A, B], option[T], or a map’s values.

You never write the types at a call. The checker works them out from the arguments, as it works out every other type, so first([3, 1, 2]) returns an int and first(["a"]) a str. A type parameter that appears only in the result, as in fn empty[T]() -> list[T]:, is worked out from how the result is used. Arguments must agree, so with fn pair[T](a: T, b: T), pair(1, "a") is an error at "a".

What a generic function can do

The checker checks a generic function’s body once, for every type T could be, so a mistake is always reported inside the function, never at a distant call. A value of type T can be assigned, passed, returned, printed, written into a string with str(x) or "{x}", and stored in lists, tuples, options, and map values. It cannot be used in arithmetic, compared with == or <, used as a condition, indexed, looped over, or matched, and its only method is display, since T might be a type that allows none of the rest. A list of T is still a list, so xs.len(), xs.append(x), and xs[0] all work on a list[T]. To give T methods, or let it be compared, bound it by a trait, as Traits shows.

Generic structs and enums

A struct or enum takes type parameters the same way, after its name: struct Pair[A, B]: holds a value of each of two types, and enum Tree[T]: is a tree of any type. Their types are written with the types filled in, as in Pair[int, str] or Tree[str], and a value fills them in from what it holds, so Pair(first=1, second="one") is a Pair[int, str] and p.first + 1 works.

The functions of a generic struct’s impl block use its type parameters without writing them again: in impl Pair:, fn swap(self) -> Pair[B, A]: returns a pair the other way around. A method can have type parameters of its own too, written after its name like a function’s: fn with_first[C](self, c: C) -> Pair[C, B]: replaces the first value with one of any type.

The compiler makes a copy of a generic function, or of a generic struct’s methods, for each set of types the program uses it with, the way Rust does, so it runs as fast as one written for a single type.

Next, Traits.