Functions

Functions are first-class values in AodhML. They can be passed as arguments, returned from other functions, and stored in variables.

Function Declaration

Use the fn keyword followed by the function name, parameters with types, and an optional return type:

fn greet(name: String) -> String {
    return "Hello, " + name + "!"
}

fn main() {
    let message = greet("AodhML")
    println(message)
}

Parameters & Return Types

All parameters must have explicit type annotations. The return type is required unless the function returns void:

fn add(a: i32, b: i32) -> i32 {
    return a + b
}

fn print_value(x: i32) {
    // No return type = void
    println(x)
}

Default Parameters

Parameters can have default values:

fn greet(name: String, greeting: String = "Hello") -> String {
    return greeting + ", " + name + "!"
}

greet("World")           // "Hello, World!"
greet("World", "Hi")     // "Hi, World!"

Higher-Order Functions

Functions can accept other functions as parameters:

fn map(arr: [i32], f: fn(i32) -> i32) -> [i32] {
    let result = []
    for x in arr {
        result.push(f(x))
    }
    return result
}

fn double(x: i32) -> i32 { return x * 2 }

fn main() {
    let nums = [1, 2, 3, 4]
    let doubled = map(nums, double)
    println(doubled)  // [2, 4, 6, 8]
}

Closures

Anonymous functions (closures) capture their enclosing scope:

fn make_multiplier(factor: i32) -> fn(i32) -> i32 {
    return |x: i32| -> i32 { x * factor }
}

fn main() {
    let triple = make_multiplier(3)
    println(triple(4))  // 12
}