45 lines
1.5 KiB
Plaintext
45 lines
1.5 KiB
Plaintext
import std::io;
|
|||
|
|
|
||
|
|
# A pattern parameter, given a signature whole.
|
||
|
|
trait handler<def(Ts...): R> {
|
||
|
|
def handle(&mut this, args: Ts...): R;
|
||
|
|
}
|
||
|
|
|
||
|
|
# What a signature names of a function type: its result, and its parameters.
|
||
|
|
def gives<F>(f: F): string where F: signature {
|
||
|
|
return $"{name_of::<F::result>()} of {name_of::<F>()}";
|
||
|
|
}
|
||
|
|
|
||
|
|
# A function over any signature, forwarding its arguments.
|
||
|
|
def forward<F>(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<F> : handler<F> where F: signature {
|
||
|
|
var call: F;
|
||
|
|
var hits: i64;
|
||
|
|
}
|
||
|
|
def wrapped<F>::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<def(i64, i64): i64>): 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::<def(i64, i64): i64>{ call = add, hits = 0 };
|
||
|
|
println($"{w.handle(1, 2)} {run(w)} hits {w.hits}");
|
||
|
|
println(name_of::<wrapped<def(i64, i64): i64>>());
|
||
|
|
var s := wrapped::<def(i64...): i64>{ call = sum, hits = 0 };
|
||
|
|
println($"{s.handle()} {s.handle(1, 2, 3)} hits {s.hits}");
|
||
|
|
}
|