comptime_closures
Closures without a GC: a closure passed to a comptime parameter is compiled
into its own instance of the function, which gets the captured values as
hidden arguments and calls the closure directly, like Rust’s impl Fn.
jihoo build examples/comptime_closures.jh -o out/cc && ./out/cc#![freestanding]import io
fn each(comptime f: fn(i64), xs: [i64; 5]) { let i = 0 while i < len(xs) { f(xs[i]) i = i + 1 }}
fn count(comptime keep: fn(i64) -> bool, xs: [i64; 5]) -> i64 { let n = 0 // A closure can be passed on, or wrapped in another one. each(fn(x) { if keep(x) { io.print_int(x) } }, xs) let i = 0 while i < len(xs) { if keep(xs[i]) { n = n + 1 } i = i + 1 } return n}
fn _start() -> i64 { let xs = [12, 7, 30, 1, 18] let limit = 10 let n = count(fn(x) { return x > limit }, xs) // prints 12, 30, 18 return n // exit status 3}