closures
This commit is contained in:
95
examples/35-closures.sx
Normal file
95
examples/35-closures.sx
Normal file
@@ -0,0 +1,95 @@
|
||||
#import "modules/std.sx";
|
||||
|
||||
// --- Closure Basics ---
|
||||
|
||||
// Factory: returns a new closure each time
|
||||
make_adder :: (n: s64) -> Closure(s64) -> s64 {
|
||||
return closure((x: s64) -> s64 => x + n);
|
||||
}
|
||||
|
||||
// Higher-order function: accepts any Closure(s64) -> s64
|
||||
apply :: (f: Closure(s64) -> s64, x: s64) -> s64 { return f(x); }
|
||||
|
||||
// Reduce: fold over a slice with a closure
|
||||
reduce :: (arr: []s64, f: Closure(s64, s64) -> s64, init: s64) -> s64 {
|
||||
acc := init;
|
||||
i : s64 = 0;
|
||||
while i < arr.len { acc = f(acc, arr[i]); i += 1; }
|
||||
return acc;
|
||||
}
|
||||
|
||||
// Auto-promoted bare function
|
||||
triple :: (x: s64) -> s64 { return x * 3; }
|
||||
|
||||
// Struct with optional closure callback
|
||||
Widget :: struct {
|
||||
name: string;
|
||||
on_update: ?Closure(s64) -> void;
|
||||
}
|
||||
|
||||
main :: () {
|
||||
// 1. Basic closure with capture
|
||||
offset := 100;
|
||||
add_offset := closure((x: s64) -> s64 => x + offset);
|
||||
print("basic: {}\n", add_offset(42));
|
||||
|
||||
// 2. Capture by value (snapshot semantics)
|
||||
n := 10;
|
||||
snap := closure((x: s64) -> s64 => x + n);
|
||||
n = 999;
|
||||
print("snapshot: {}\n", snap(5));
|
||||
|
||||
// 3. Block-body closure with control flow
|
||||
clamp := closure((x: s64) -> s64 {
|
||||
if x < 0 { return 0; }
|
||||
if x > 100 { return 100; }
|
||||
return x;
|
||||
});
|
||||
print("clamp: {} {} {}\n", clamp(50), clamp(0 - 10), clamp(200));
|
||||
|
||||
// 4. Void closure with string capture
|
||||
tag := "INFO";
|
||||
logger := closure((msg: string) {
|
||||
print("[{}] {}\n", tag, msg);
|
||||
});
|
||||
logger("system ready");
|
||||
|
||||
// 5. Factory pattern
|
||||
add5 := make_adder(5);
|
||||
add10 := make_adder(10);
|
||||
print("factory: {} {}\n", add5(100), add10(100));
|
||||
|
||||
// 6. Auto-promotion: bare fn passed where Closure expected
|
||||
print("auto-promote: {}\n", apply(triple, 7));
|
||||
|
||||
// 7. Closure passed to higher-order function
|
||||
factor := 4;
|
||||
print("hof: {}\n", apply(closure((x: s64) -> s64 => x * factor), 10));
|
||||
|
||||
// 8. Reduce with closure
|
||||
nums : []s64 = .[1, 2, 3, 4, 5];
|
||||
total := reduce(nums, closure((acc: s64, x: s64) -> s64 => acc + x), 0);
|
||||
print("reduce: {}\n", total);
|
||||
|
||||
// 9. Closure captures closure
|
||||
inner := closure((x: s64) -> s64 => x + 10);
|
||||
outer := closure((x: s64) -> s64 => inner(x) * 2);
|
||||
print("compose: {}\n", outer(5));
|
||||
|
||||
// 10. Multiple closures from same scope
|
||||
base := 100;
|
||||
cl_add := closure((x: s64) -> s64 => x + base);
|
||||
cl_mul := closure((x: s64) -> s64 => x * base);
|
||||
print("multi: {} {}\n", cl_add(5), cl_mul(5));
|
||||
|
||||
// 11. Optional closures
|
||||
w1 := Widget.{ name = "slider", on_update = closure((val: s64) {
|
||||
print("widget: {} = {}\n", "slider", val);
|
||||
}) };
|
||||
w2 := Widget.{ name = "label", on_update = null };
|
||||
|
||||
if h := w1.on_update { h(42); }
|
||||
if h := w2.on_update { h(0); } else { print("widget: no handler\n"); }
|
||||
|
||||
print("=== DONE ===\n");
|
||||
}
|
||||
@@ -1719,5 +1719,239 @@ END;
|
||||
print("guard loop: {}\n", guard_loop(3)); // guard loop: 3
|
||||
}
|
||||
|
||||
// --- block-body lambdas ---
|
||||
{
|
||||
// block-body lambda with return type
|
||||
clamp := (x: s64, lo: s64, hi: s64) -> s64 {
|
||||
if x < lo { return lo; }
|
||||
if x > hi { return hi; }
|
||||
return x;
|
||||
};
|
||||
print("block-lambda: {}\n", clamp(50, 0, 100)); // block-lambda: 50
|
||||
print("block-lambda: {}\n", clamp(-10, 0, 100)); // block-lambda: 0
|
||||
print("block-lambda: {}\n", clamp(999, 0, 100)); // block-lambda: 100
|
||||
|
||||
// block-body lambda without return type annotation
|
||||
greet := (name: string) {
|
||||
print("hello {}\n", name);
|
||||
};
|
||||
greet("block"); // hello block
|
||||
}
|
||||
|
||||
// --- named params in function types ---
|
||||
{
|
||||
// Named params are documentation only — ignored for type identity
|
||||
apply_named :: (f: (x: s32, y: s32) -> s32, a: s32, b: s32) -> s32 {
|
||||
return f(a, b);
|
||||
}
|
||||
add :: (a: s32, b: s32) -> s32 { return a + b; }
|
||||
print("named-fn-type: {}\n", apply_named(add, 3, 4)); // named-fn-type: 7
|
||||
}
|
||||
|
||||
// --- xx on function pointers ---
|
||||
{
|
||||
MyEnv :: struct { n: s32; }
|
||||
typed_fn :: (e: *MyEnv, x: s32) -> s32 {
|
||||
return x + e.n;
|
||||
}
|
||||
// xx cast: (*MyEnv, s32) -> s32 → (*void, s32) -> s32
|
||||
f : (*void, s32) -> s32 = xx typed_fn;
|
||||
env := MyEnv.{ n = 100 };
|
||||
print("xx-fnptr: {}\n", f(xx @env, 42)); // xx-fnptr: 142
|
||||
}
|
||||
|
||||
// --- closure type: construct and access fields ---
|
||||
{
|
||||
dummy_fn :: (env: *void, x: s32) -> s32 {
|
||||
return x * 2;
|
||||
}
|
||||
fn_ptr : *void = xx dummy_fn;
|
||||
null_env : *void = xx 0;
|
||||
c : Closure(s32) -> s32 = .{ fn_ptr = fn_ptr, env = null_env };
|
||||
print("closure-type: fn_ptr-nonnull={}\n", c.fn_ptr != null_env);
|
||||
print("closure-type: env-null={}\n", c.env == null_env);
|
||||
}
|
||||
|
||||
// --- closure calling convention ---
|
||||
{
|
||||
Env :: struct { n: s32; }
|
||||
impl :: (env: *void, x: s32) -> s32 {
|
||||
e : *Env = xx env;
|
||||
return x + e.n;
|
||||
}
|
||||
env := Env.{ n = 5 };
|
||||
fn_ptr : *void = xx impl;
|
||||
env_ptr : *void = xx @env;
|
||||
c : Closure(s32) -> s32 = .{ fn_ptr = fn_ptr, env = env_ptr };
|
||||
print("closure-call: {}\n", c(10));
|
||||
}
|
||||
|
||||
// --- auto-promotion: bare fn → Closure ---
|
||||
{
|
||||
double :: (x: s32) -> s32 { return x * 2; }
|
||||
apply :: (f: Closure(s32) -> s32, x: s32) -> s32 { return f(x); }
|
||||
print("auto-promote: {}\n", apply(double, 10));
|
||||
|
||||
// Named function to Closure variable
|
||||
f : Closure(s32) -> s32 = double;
|
||||
print("auto-promote-var: {}\n", f(5));
|
||||
}
|
||||
|
||||
// --- closure() intrinsic ---
|
||||
{
|
||||
// capture scalar
|
||||
n := 42;
|
||||
f := closure((x: s32) => x + n);
|
||||
print("closure-capture: {}\n", f(10));
|
||||
|
||||
// capture by value is a snapshot
|
||||
m := 5;
|
||||
g := closure((x: s32) => x + m);
|
||||
m = 100;
|
||||
print("closure-snapshot: {}\n", g(10));
|
||||
|
||||
// no captures (null env)
|
||||
h := closure((x: s32) => x * 2);
|
||||
print("closure-nocap: {}\n", h(7));
|
||||
|
||||
// multiple captures
|
||||
a := 10;
|
||||
b := 20;
|
||||
multi := closure((x: s32) => x + a + b);
|
||||
print("closure-multi: {}\n", multi(3));
|
||||
|
||||
// block-body closure with return
|
||||
offset := 50;
|
||||
clamp := closure((x: s64) -> s64 {
|
||||
if x < 0 { return 0; }
|
||||
if x > 100 { return 100; }
|
||||
return x + offset;
|
||||
});
|
||||
// Workaround: assign result with explicit type so print wraps correctly
|
||||
r1 : s64 = clamp(10);
|
||||
r2 : s64 = clamp(0 - 5);
|
||||
r3 : s64 = clamp(999);
|
||||
print("closure-block: {}\n", r1);
|
||||
print("closure-block: {}\n", r2);
|
||||
print("closure-block: {}\n", r3);
|
||||
|
||||
// void closure
|
||||
tag := "LOG";
|
||||
logger := closure((msg: string) {
|
||||
print("[{}] {}\n", tag, msg);
|
||||
});
|
||||
logger("hello");
|
||||
|
||||
// pass closure to higher-order function
|
||||
dbl :: (x: s32) -> s32 { return x * 2; }
|
||||
apply_cl :: (f2: Closure(s32) -> s32, x: s32) -> s32 { return f2(x); }
|
||||
factor : s32 = 3;
|
||||
print("closure-hof: {}\n", apply_cl(closure((x: s32) -> s32 => x * factor), 10));
|
||||
|
||||
// auto-promoted bare fn passed alongside closures
|
||||
print("closure-hof-bare: {}\n", apply_cl(dbl, 10));
|
||||
|
||||
// C5.A2: capture f32
|
||||
scale := 2.5;
|
||||
f_f32 := closure((x: f32) -> f32 => x * scale);
|
||||
print("closure-f32: {}\n", f_f32(4.0));
|
||||
|
||||
// C5.A3: capture bool
|
||||
verbose := true;
|
||||
f_bool := closure((msg: string) {
|
||||
if verbose { print("closure-bool: {}\n", msg); }
|
||||
});
|
||||
f_bool("hello");
|
||||
|
||||
// C5.B3: two params
|
||||
base : s32 = 100;
|
||||
f_2p := closure((x: s32, y: s32) -> s32 => x + y + base);
|
||||
print("closure-2p: {}\n", f_2p(3, 4));
|
||||
|
||||
// C5.B4: three params
|
||||
bias : s32 = 1;
|
||||
f_3p := closure((a: s32, b: s32, c2: s32) -> s32 => a + b + c2 + bias);
|
||||
print("closure-3p: {}\n", f_3p(10, 20, 30));
|
||||
|
||||
// C5.B5: mixed param types (string + s32)
|
||||
extra : s32 = 5;
|
||||
f_mix := closure((name: string, age: s32) {
|
||||
print("closure-mix: {} is {}\n", name, age + extra);
|
||||
});
|
||||
f_mix("Alice", 30);
|
||||
|
||||
// C5.C3: return bool
|
||||
threshold : s32 = 100;
|
||||
f_rbool := closure((x: s32) -> bool { return x > threshold; });
|
||||
print("closure-rbool: {} {}\n", f_rbool(50), f_rbool(200));
|
||||
|
||||
// C5.D3: reduce / fold
|
||||
reduce :: (arr: []s32, f3: Closure(s32, s32) -> s32, init: s32) -> s32 {
|
||||
acc := init;
|
||||
i : s64 = 0;
|
||||
while i < arr.len { acc = f3(acc, arr[i]); i += 1; }
|
||||
return acc;
|
||||
}
|
||||
r_nums : []s32 = .[1, 2, 3, 4, 5];
|
||||
r_bonus : s32 = 100;
|
||||
r_total := reduce(r_nums, closure((acc: s32, x: s32) -> s32 => acc + x), r_bonus);
|
||||
print("closure-reduce: {}\n", r_total);
|
||||
|
||||
// C5.G1: factory function
|
||||
make_adder :: (n: s32) -> Closure(s32) -> s32 {
|
||||
return closure((x: s32) -> s32 => x + n);
|
||||
}
|
||||
add5 := make_adder(5);
|
||||
add10 := make_adder(10);
|
||||
print("closure-factory: {} {}\n", add5(100), add10(100));
|
||||
|
||||
// C5.A5: capture struct
|
||||
Point :: struct { x: s32; y: s32; }
|
||||
origin := Point.{ x = 10, y = 20 };
|
||||
f_st := closure(() {
|
||||
print("closure-struct: {} {}\n", origin.x, origin.y);
|
||||
});
|
||||
f_st();
|
||||
|
||||
// C5.H1: closure captures another closure
|
||||
inner_n := 10;
|
||||
inner_cl := closure((x: s64) -> s64 => x + inner_n);
|
||||
outer_cl := closure((x: s64) -> s64 => inner_cl(x) * 2);
|
||||
print("closure-compose: {}\n", outer_cl(5));
|
||||
|
||||
// C5.M7: multiple closures from same scope capture independently
|
||||
shared : s32 = 10;
|
||||
cl_a := closure((x: s32) -> s32 => x + shared);
|
||||
cl_b := closure((x: s32) -> s32 => x * shared);
|
||||
print("closure-indep: {} {}\n", cl_a(5), cl_b(5));
|
||||
|
||||
// C6: optional closures
|
||||
f_none : ?Closure(s64) -> s64 = null;
|
||||
if h := f_none {
|
||||
print("should not print: {}\n", h(1));
|
||||
} else {
|
||||
print("opt-closure: none\n");
|
||||
}
|
||||
|
||||
opt_n := 10;
|
||||
f_some : ?Closure(s64) -> s64 = closure((x: s64) -> s64 => x + opt_n);
|
||||
if h := f_some {
|
||||
print("opt-closure: {}\n", h(5));
|
||||
} else {
|
||||
print("should not print\n");
|
||||
}
|
||||
|
||||
// Struct with optional closure callback
|
||||
Btn :: struct { label: string; on_click: ?Closure(s64) -> void; }
|
||||
btn_x := 99;
|
||||
btn_cl := closure((id: s64) {
|
||||
print("opt-closure-btn: {} {}\n", id, btn_x);
|
||||
});
|
||||
btn1 := Btn.{ label = "OK", on_click = btn_cl };
|
||||
btn2 := Btn.{ label = "Cancel", on_click = null };
|
||||
if h := btn1.on_click { h(1); }
|
||||
if h := btn2.on_click { h(2); } else { print("opt-closure-btn: null\n"); }
|
||||
}
|
||||
|
||||
print("=== DONE ===\n");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user