import std::io; type transform = def(int): int; struct counter { var count: int; } # A closure refers to the locals it uses, so what outlives the function making it # is a functor: a struct holding what it uses, called through `invoke`. struct bumper : invokable { var target: &mut counter; } def bumper::invoke(&mut this): void { this.target.count++; } def counter::incrementer(this: &mut counter): bumper { return bumper{ target = this }; } def double(n: int): int { return n * 2; } def map(values: int[4], f: F): int[4] where F: invokable { var out: int[4]; for i, v in values { out[i] = f(v); } return out; } def fold(values: int[4], start: int, f: def(int, int): int): int { var acc := start; for v in values { acc = f(acc, v); } return acc; } struct composed : invokable where F: invokable where G: invokable { var first: F; var then: G; } def composed::invoke(&mut this, x: int): int { val first := &mut this.first; val then := &mut this.then; return then(first(x)); } def compose(f: F, g: G): composed where F: invokable where G: invokable { return composed::{ first = f, then = g }; } struct adds : invokable { var n: int; } def adds::invoke(&mut this, x: int): int { return x + this.n; } def adder(n: int): adds { return adds{ n = n }; } struct count_up : invokable { var count: int; } def count_up::invoke(&mut this): int { this.count++; return this.count; } def make_counter(): count_up { return count_up{}; } struct scale : invokable { var by: int; } def scale::invoke(&mut this, x: int): int { return x * this.by; } val square := def(x: int): int { return x * x; }; def main(): void { val values := [1, 2, 3, 4]; print($"{map(values, double)} {fold(values, 0, def(a: int, b: int): int { return a + b; })} "); print($"{map(values, compose(adder(1), square))} {square} "); var next := make_counter(); var other := make_counter(); next(); next(); print($"{next()} {other()} "); var total := 0; val add := def(x: int): void { total += x; }; for v in values { add(v); } var fns: scale[4]; for at, i in values { fns[at] = scale{ by = i }; } var fib: transform = double; fib = def(n: int): int { return n < 2 ? n : fib(n - 1) + fib(n - 2); }; var c := counter{}; var inc := c.incrementer(); inc(); inc(); println($"{total} {fns[0](10)} {fns[3](10)} {fib(12)} {c.count} {(def(): int { return 7; })()}"); }