import std::io; # A pattern parameter, given a signature whole. trait handler { def handle(&mut this, args: Ts...): R; } # What a signature names of a function type: its result, and its parameters. def gives(f: F): string where F: signature { return $"{name_of::()} of {name_of::()}"; } # A function over any signature, forwarding its arguments. def forward(f: F, args: F::params...): F::result where F: signature { return f(...args); } # A functor over any signature, which calls the function it holds. struct wrapped : handler where F: signature { var call: F; var hits: i64; } def wrapped::handle(&mut this, args: F::params...): F::result { this.hits += 1; return this.call(...args); } def sum(xs: i64...): i64 { var t: i64 = 0; for x in xs { t += x; } return t; } def add(a: i64, b: i64): i64 { return a + b; } def greet(name: strview): string { return $"hi {name}"; } def run(h: &mut handler): i64 { return h.handle(4, 5); } def main(): void { println(gives(add)); println(gives(sum)); println(gives(greet)); println($"{forward(add, 1, 2)} {forward(sum, 1, 2, 3)} {forward(sum)}"); println(forward(greet, "you")); var w := wrapped::{ call = add, hits = 0 }; println($"{w.handle(1, 2)} {run(w)} hits {w.hits}"); println(name_of::>()); var s := wrapped::{ call = sum, hits = 0 }; println($"{s.handle()} {s.handle(1, 2, 3)} hits {s.hits}"); }