Files
sakurac/tests/programs/refined_functions_as_values_1.sakura
T
2026-11-19 04:54:17 -06:00

48 lines
2.0 KiB
Plaintext

import std::io;
struct failure { val message: span<u8>; }
union value { var whole: int; var real: float; var text: span<u8>; }
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<u8>, 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<def(int): int> { 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<u8>; 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()}");
}