51 lines
2.3 KiB
Plaintext
51 lines
2.3 KiB
Plaintext
import std::io;
|
|
|
|
struct adder : invokable<def(i64, i64): i64> { var calls: i64; }
|
|
def adder::invoke(&mut this, a: i64, b: i64): i64 { this.calls++; return a + b; }
|
|
|
|
# A stateless functor takes `&this`, which meets the trait's `&mut this`.
|
|
struct doubler : invokable<def(i64): i64> {}
|
|
def doubler::invoke(&this, x: i64): i64 { return x * 2; }
|
|
|
|
# Both `&this` and `&mut this`: what can be written calls the second.
|
|
struct both : invokable<def(): strview> {}
|
|
def both::invoke(&this): strview { return "read"; }
|
|
def both::invoke(&mut this): strview { return "written"; }
|
|
|
|
# Wider arguments and results, through a trait reference.
|
|
struct labeler : invokable<def(strview, i64): string> { var prefix: strview; }
|
|
def labeler::invoke(&mut this, name: strview, n: i64): string { return $"{this.prefix}{name}#{n}"; }
|
|
|
|
# A variadic signature, through a trait reference.
|
|
struct summer : invokable<def(i64...): i64> {}
|
|
def summer::invoke(&mut this, xs: i64...): i64 { var t: i64 = 0; for x in xs { t += x; } return t; }
|
|
|
|
# A functor over any signature, which calls the function it holds.
|
|
struct wrapped<F> : invokable<F> where F: signature { var call: F; var hits: i64; }
|
|
def wrapped<F>::invoke(&mut this, args: F::params...): F::result { this.hits++; return this.call(...args); }
|
|
|
|
def twice<F>(f: &mut F, x: i64): i64 where F: invokable<def(i64): i64> { return f.invoke(f.invoke(x)); }
|
|
def run(f: &mut invokable<def(i64, i64): i64>): i64 { return f.invoke(10, 20); }
|
|
def run1(f: &mut invokable<def(i64): i64>): i64 { return f.invoke(21); }
|
|
def say(f: &mut invokable<def(): strview>): strview { return f.invoke(); }
|
|
def label(f: &mut invokable<def(strview, i64): string>): string { return f.invoke("item", 7); }
|
|
def total(f: &mut invokable<def(i64...): i64>): i64 { return f.invoke(1, 2, 3); }
|
|
|
|
def square(x: i64): i64 { return x * x; }
|
|
|
|
def main(): void {
|
|
var a := adder{};
|
|
println($"{a.invoke(1, 2)} {run(a)} calls {a.calls}");
|
|
var d := doubler{};
|
|
println($"{twice(&mut d, 3)} {run1(d)}");
|
|
var b := both{};
|
|
val r := both{};
|
|
println($"{b.invoke()} {r.invoke()} {say(b)}");
|
|
var l := labeler{ prefix = "#" };
|
|
println(label(l));
|
|
var s := summer{};
|
|
println($"{total(s)} {s.invoke()}");
|
|
var w := wrapped::<def(i64): i64>{ call = square, hits = 0 };
|
|
println($"{twice(&mut w, 3)} {run1(w)} hits {w.hits}");
|
|
}
|