import std::io; struct failure { val message: span; } union value { var whole: int; var real: float; var text: span; } union reading { var value: value; var failure: failure; } union callable { var failure: failure; var call: def(int): int; } struct counter { var count: int; } def counter::add(this: &mut counter, by: int): int { this.count += by; return this.count; } def apply(f: def(int): int, x: int): int { return f(x); } def read(text: span, fail: bool): reading { return fail ? reading{ failure = failure{ message = text } } : reading{ value = value{ text = text } }; } def shown(given: &value): string { return given is text ? given.text : "other"; } # A closure refers to the locals it uses, so what outlives the function making it # holds what it uses itself, as a functor. struct adding : invokable { var local: counter; } def adding::invoke(&mut this, by: int): int { return this.local.add(by); } def taken(): adding { return adding{ local = counter{ count = 100 } }; } struct command { val name: span; var run: def(&command): void = idle; } def idle(cmd: &command): void {} def main(): void { def fib(n: int): int { return n < 2 ? n : fib(n - 1) + fib(n - 2); } print($"{apply(def(x) => x * 3, 5)} {apply(def(x) { return x + 1; }, 5)} "); val inferred := def(x: int) => x * x; print($"{inferred(7)} "); var c := counter{}; val add := counter::add; add(c, 2); print($"{apply(def(x) => c.add(x), 3)} {c.count} "); var kept := taken(); kept(1); print($"{kept(1)} "); print($"{fib(15)} "); var cmd := command{ name = "go" }; cmd.run(&cmd); cmd.run = def(me) => print($"{me.name} "); cmd.run(&cmd); val ok := read("yes", false); val bad := read("no", true); val v := value{ text = "text" }; val nested := reading{ value = value{ real = 1.5 } }; print($"{ok} {bad.failure.message} {shown(&v)} {nested} "); val either := callable{ call = def(x) => x - 1 }; val maybe: def(): int = c.count > 0 ? def() => 9 : def() => 0; println($"{either.call(10)} {maybe()}"); }