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

A closure can capture a parameter or an enclosing function's captured value. Captured variables can be updated through the closure and retain that update between calls:

fn create_counter(count) {
    return fn() {
        set count = count + 1
        return count
    }
}

set counter = create_counter(0)
print(counter())
print(counter())

Each call to create_counter receives its own parameter value, so its returned closure has independent counter state. Within a function, parameters are local; a name introduced only by set is not a new local variable and may resolve to a global instead.

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.