import std::io; struct adder : invokable { 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 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 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 { 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 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 : invokable where F: signature { var call: F; var hits: i64; } def wrapped::invoke(&mut this, args: F::params...): F::result { this.hits++; return this.call(...args); } def twice(f: &mut F, x: i64): i64 where F: invokable { return f.invoke(f.invoke(x)); } def run(f: &mut invokable): i64 { return f.invoke(10, 20); } def run1(f: &mut invokable): i64 { return f.invoke(21); } def say(f: &mut invokable): strview { return f.invoke(); } def label(f: &mut invokable): string { return f.invoke("item", 7); } def total(f: &mut invokable): 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::{ call = square, hits = 0 }; println($"{twice(&mut w, 3)} {run1(w)} hits {w.hits}"); }