import std::io; # A pattern parameter is given a function type, and names its parts. trait handler { def handle(&mut this, args: Ts...): R; } struct adder : handler { var calls: i64; } def adder::handle(&mut this, a: i64, b: i64): i64 { this.calls++; return a + b; } struct shout : handler {} def shout::handle(&mut this, text: strview): string { var out: string = text; out.append("!"); return out; } def twice(g: &mut G, x: i64, y: i64): i64 where G: handler { return g.handle(g.handle(x, y), y); } def call_with(g: &mut G, args: Ts...): R where G: handler { return g.handle(...args); } def run(g: &mut handler): i64 { return g.handle(10, 20); } # A struct whose own parameters are a pattern's. struct counter : handler where R: zeroable { var hits: i64; } def counter::handle(&mut this, args: Ts...): R { this.hits += 1 + args.length as i64; var out: R; return out; } # A pattern's result may be `void`, as a function's may. struct tally : handler { var sum: i64; } def tally::handle(&mut this, x: i64): void { this.sum += x; } def feed(h: &mut handler): void { h.handle(4); h.handle(5); } # A struct with a pattern beside a plain parameter. struct pair { var key: K; } # A variadic signature's parameters are those of a variadic function. struct summer : handler {} def summer::handle(&mut this, xs: i64...): i64 { var t: i64 = 0; for x in xs { t += x; } return t; } def total(f: &mut handler): i64 { return f.handle(1, 2, 3, 4); } # Names before a pack take one parameter each, beside a plain parameter. trait first { def head(&this, a: A): R; def rest(&this, args: Rest...): K; } struct picker : first {} def picker::head(&this, a: i64): u8 { return a as u8; } def picker::rest(&this, b: bool, s: strview): u64 { return s.length; } def main(): void { var a := adder{}; println($"{a.handle(1, 2)} {twice(&mut a, 1, 2)} {run(a)} calls {a.calls}"); var s := shout{}; val loud: string = call_with(&mut s, "hey"); println(loud); var c := counter::{}; println($"{c.handle(1, true)} hits {c.hits}"); var m := summer{}; println($"{m.handle()} {m.handle(5)} {total(m)}"); val p := picker{}; println($"{p.head(300)} {p.rest(true, "four")}"); println(name_of::>()); println(name_of::>()); println(name_of::>()); println(name_of::>()); var t := tally{}; feed(t); println($"void {t.sum}"); }