Functions & Closures
Define, call, and compose functions with Kria.
Named Functions
Define a function with the fn keyword, followed by a name and parameters:
fn add(a, b) {
return a + b
}
fn greet(name) {
print("Hello, ")
print(name)
}
print(add(5, 3))
greet("Kria")
Functions can have zero or more parameters. They are called by name with parentheses.
Parameters & Return Values
Functions receive parameters and return values with the return keyword:
fn get_max(a, b) {
if (a > b) {
return a
} else {
return b
}
}
set max_val = get_max(15, 8)
print(max_val)
A function can have multiple return statements.
If no return is given, the function returns null.
Lambda Functions
Create anonymous functions inline using the same fn syntax:
set double = fn(x) {
return x * 2
}
print(double(10))
set create_multiplier = fn(factor) {
return fn(x) {
return x * factor
}
}
set times_three = create_multiplier(3)
print(times_three(7))
Lambdas can be assigned to variables or passed as arguments. They support nested definitions.
Closures
Functions can capture variables from their enclosing scope (closure). Captured values are copied when the function is created (copy-on-create semantics):
fn create_counter() {
set count = 0
return fn() {
set count = count + 1
return count
}
}
set counter = create_counter()
print(counter())
print(counter())
Each function has its own copy of captured variables, so they don't interfere with each other.
Recursion
Functions can call themselves recursively:
fn factorial(n) {
if (n <= 1) {
return 1
} else {
set prev = n - 1
set prev_factorial = factorial(prev)
return n * prev_factorial
}
}
print(factorial(5))
Ensure your recursive function has a base case to prevent infinite recursion.