generics

Generics are compile-time parameters, as in Zig: comptime T: type, or comptime T: Ord to ask for a trait. Each set of arguments compiles to its own copy, so generic code is as fast as code written by hand. Type arguments are inferred where they can be.

jihoo run examples/generics.jh
struct Stack(T: type) {
    items: Vec(T)
}

impl(T: type) Stack(T) {
    fn new() -> Stack(T) {
        Stack(T) { items: Vec.new() }
    }
    fn push(inout self, sink x: T) {
        self.items.push(x)
    }
    fn pop(inout self) -> Option(T) {
        self.items.pop()
    }
}

trait Shape {
    fn area(self) -> f64
    fn describe(self) -> String {
        "a shape of area " + (self.area() as i64).to_string()
    }
}

struct Square {
    side: f64
}

impl Shape for Square {
    fn area(self) -> f64 {
        self.side * self.side
    }
}

fn largest(comptime T: Ord, xs: [T]) -> T {
    var best = xs[0].clone()
    for x in xs {
        if x > best {
            best = x.clone()
        }
    }
    best
}

fn main() {
    var s = Stack(String).new()
    s.push("a")
    s.push("b")
    println(s.pop().unwrap())
    println(Square { side: 3.0 }.describe())
    println(largest([3, 9, 4]))
    println(largest(["pear", "fig", "plum"]))
}

View on GitHub

Esc