Skip to content

closures

Closures borrow what they use, so they cost no allocation. A parameter of type fn(A) -> R takes one; a comptime one gets a copy of the function per closure, where the closure is inlined.

Terminal window
jihoo run examples/closures.jh
examples/closures.jh
fn count_if(xs: [i64], pred: fn(i64) -> bool) -> i64 {
var n = 0
for x in xs {
if pred(x) {
n += 1
}
}
n
}
fn apply_all(inout xs: Vec(i64), comptime f: fn(i64) -> i64) {
for i in 0..xs.len() {
xs[i] = f(xs[i])
}
}
fn main() {
let limit = 10
var v = Vec(i64).new()
for i in 0..20 {
v.push(i)
}
println(count_if(v.as_slice(), fn(x) { x > limit }))
var total = 0
apply_all(&v, fn(x) { x * x })
for x in v {
total += x
}
println(total)
sort_by(&v, fn(a, b) { a > b })
println(v[0])
}

View on GitHub