Initial Commit
This commit is contained in:
789 files changed
+149185
No files matched your search
@@ -0,0 +1,56 @@
|
||||
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; }
|
||||
|
||||
struct doubler {}
|
||||
def doubler::invoke(&this, x: i64): i64 { return x * 2; }
|
||||
|
||||
# Overloads are chosen by their arguments, as a method's are.
|
||||
struct shape {}
|
||||
def shape::invoke(&this, x: i64): strview { return "int"; }
|
||||
def shape::invoke(&this, x: strview): strview { return "text"; }
|
||||
|
||||
struct holder { var f: adder; var g: doubler; }
|
||||
def make(): doubler { return doubler{}; }
|
||||
|
||||
def twice<F>(f: &mut F, x: i64): i64 where F: invokable<def(i64): i64> { return f(f(x)); }
|
||||
def run(f: &mut invokable<def(i64, i64): i64>): i64 { return f(10, 20); }
|
||||
def run1(f: &mut invokable<def(i64): i64>): i64 { return f(5); }
|
||||
def total(f: &mut invokable<def(i64...): i64>): i64 { return f(1, 2, 3); }
|
||||
def say(f: &mut invokable<def(strview, i64): string>): string { return f("ab", 3); }
|
||||
def tell(f: &mut invokable<def(strview): void>): void { f("told"); }
|
||||
|
||||
def square(x: i64): i64 { return x * x; }
|
||||
def sum(xs: i64...): i64 { var t: i64 = 0; for x in xs { t += x; } return t; }
|
||||
def greet(name: strview, times: i64): string { var out: string = ""; for i in 0..times { out.append(name); } return out; }
|
||||
def shout(text: strview): void { println(text); }
|
||||
|
||||
def main(): void {
|
||||
# A value of a type with an `invoke` is called as a function is.
|
||||
var a := adder{};
|
||||
_ = a(1, 2);
|
||||
println($"{a(3, 4)} calls {a.calls}");
|
||||
val d := doubler{};
|
||||
println($"{d(5)} {make()(6)}");
|
||||
var h := holder{ f = adder{}, g = doubler{} };
|
||||
println($"{h.f(1, 1)} {h.g(7)} calls {h.f.calls}");
|
||||
val r: &mut adder = &mut a;
|
||||
println($"{r(2, 2)} {run(a)} calls {a.calls}");
|
||||
var t := doubler{};
|
||||
println($"{twice(&mut t, 3)}");
|
||||
val s := shape{};
|
||||
println($"{s(1)} {s("one")}");
|
||||
|
||||
# A function value is `invokable` of its own type, through its `invoke`.
|
||||
var sq: def(i64): i64 = square;
|
||||
println($"{sq.invoke(4)} {twice(&mut sq, 3)} {run1(sq)}");
|
||||
var lam := def(x: i64): i64 => x + 100;
|
||||
println($"{twice(&mut lam, 1)} {run1(lam)}");
|
||||
var all: def(i64...): i64 = sum;
|
||||
println($"{all.invoke(1, 2)} {total(all)}");
|
||||
var g := greet;
|
||||
println(say(g));
|
||||
var sh := shout;
|
||||
tell(sh);
|
||||
}
|
||||
Reference in new issue
Block a user