Higher-Order Functions
Functions are first-class values in Kira. You can pass them as arguments and return them from other functions.
Passing Functions as Arguments
fn apply(f: fn(i32) -> i32, x: i32) -> i32 {
return f(x)
}
let double: fn(i32) -> i32 = fn(x: i32) -> i32 { return x * 2 }
let result: i32 = apply(double, 5) // 10Returning Functions
fn make_adder(n: i32) -> fn(i32) -> i32 {
return fn(x: i32) -> i32 { return x + n }
}
let add_five: fn(i32) -> i32 = make_adder(5)
let result: i32 = add_five(10) // 15Common Higher-Order Patterns
Map
Transform each element of a list:
let numbers: List[i32] = Cons(1, Cons(2, Cons(3, Nil)))
let doubled: List[i32] = std.list.map[i32, i32](
numbers,
fn(x: i32) -> i32 { return x * 2 }
)
// [2, 4, 6]Filter
Keep elements matching a predicate:
let evens: List[i32] = std.list.filter[i32](
numbers,
fn(x: i32) -> bool { return x % 2 == 0 }
)
// [2]Fold
Reduce a list to a single value:
let sum: i32 = std.list.fold[i32, i32](
numbers,
0,
fn(acc: i32, x: i32) -> i32 { return acc + x }
)
// 6Anonymous Functions (Lambdas)
fn(x: i32) -> i32 { return x * 2 }
fn(a: i32, b: i32) -> i32 { return a + b }
fn() -> void { std.io.println("Hello") }Anonymous functions follow the same rules as named functions: all parameter types and return types must be explicit.