ir
This commit is contained in:
80
examples/test_bus.sx
Normal file
80
examples/test_bus.sx
Normal file
@@ -0,0 +1,80 @@
|
||||
#import "modules/std.sx";
|
||||
|
||||
main :: () {
|
||||
n1 : s32 = 1;
|
||||
n2 : s32 = 2;
|
||||
n3 : s32 = 3;
|
||||
|
||||
f1 := closure((x: s32) -> s32 => x + n1);
|
||||
f2 := closure((x: s32) -> s32 => x + n2);
|
||||
f3 := closure((x: s32) -> s32 => x + n3);
|
||||
|
||||
print("f1: {}\n", f1(10));
|
||||
print("f2: {}\n", f2(10));
|
||||
print("f3: {}\n", f3(10));
|
||||
|
||||
// closure struct field
|
||||
Button :: struct {
|
||||
label: string;
|
||||
on_press: Closure(s32) -> void;
|
||||
}
|
||||
btn_val := 99;
|
||||
btn_cb := closure((id: s32) {
|
||||
print("btn: {} {}\n", id, btn_val);
|
||||
});
|
||||
btn := Button.{ label = "OK", on_press = btn_cb };
|
||||
btn.on_press(1);
|
||||
|
||||
// optional closure
|
||||
f_none : ?Closure(s64) -> s64 = null;
|
||||
if f_none != null { print("should not print\n"); }
|
||||
else { print("opt-closure: none\n"); }
|
||||
|
||||
// closure factory
|
||||
make_adder :: (n: s32) -> Closure(s32) -> s32 {
|
||||
closure((x: s32) -> s32 => x + n);
|
||||
}
|
||||
add5 := make_adder(5);
|
||||
add10 := make_adder(10);
|
||||
print("factory: {} {}\n", add5(100), add10(100));
|
||||
|
||||
// HOF compose
|
||||
compose :: (f: Closure(s32) -> s32, g: Closure(s32) -> s32) -> Closure(s32) -> s32 {
|
||||
closure((x: s32) -> s32 => f(g(x)));
|
||||
}
|
||||
double :: (x: s32) -> s32 { return x * 2; }
|
||||
cf := compose(add5, double);
|
||||
print("compose: {}\n", cf(10));
|
||||
|
||||
// closure with array
|
||||
sort_bubble :: (arr: [*]s32, cnt: s64, less: Closure(s32, s32) -> bool) {
|
||||
i : s64 = 0;
|
||||
while i < cnt {
|
||||
j : s64 = 0;
|
||||
while j < cnt - 1 {
|
||||
if less(arr[j + 1], arr[j]) {
|
||||
tmp := arr[j];
|
||||
arr[j] = arr[j + 1];
|
||||
arr[j + 1] = tmp;
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
sort_arr : [5]s32 = .[5, 3, 1, 4, 2];
|
||||
sort_bubble(xx @sort_arr, 5, closure((a: s32, b: s32) -> bool {
|
||||
return a < b;
|
||||
}));
|
||||
print("sort: {} {} {} {} {}\n", sort_arr[0], sort_arr[1], sort_arr[2], sort_arr[3], sort_arr[4]);
|
||||
|
||||
// Many closures with string captures
|
||||
tag1 := "hello";
|
||||
tag2 := "world";
|
||||
sf1 := closure((x: s32) { print("sf1: {} {}\n", tag1, x); });
|
||||
sf2 := closure((x: s32) { print("sf2: {} {}\n", tag2, x); });
|
||||
sf1(1);
|
||||
sf2(2);
|
||||
|
||||
print("=== DONE ===\n");
|
||||
}
|
||||
Reference in New Issue
Block a user