Functions & Lambdas — Mapanare
Named functions, closures, generics, and first-class function values.
Function Definitions
Functions are declared with fn. Parameter types and the return type are always annotated. If the return type is omitted, it defaults to Void.
fn greet(name: String) {
print("Hello, " + name)
}
fn add(a: Int, b: Int) -> Int {
return a + b
}
Visibility
Functions are private by default. Use pub to make them accessible from other modules.
Generic Functions
fn identity<T>(x: T) -> T {
return x
}
let n = identity(42) // T = Int
let s = identity("hello") // T = String
Trait Bounds
fn max<T: Ord>(a: T, b: T) -> T {
if a.cmp(b) > 0 { return a }
return b
}
fn print_all<T: Display>(items: List<T>) {
for item in items { println(item.to_string()) }
}
Lambda Expressions
let double = x => x * 2
let add = (a, b) => a + b
let evens = nums |> filter(x => x % 2 == 0)
Function Types
fn apply(f: fn(Int) -> Int, x: Int) -> Int {
return f(x)
}
type Predicate = fn(Int) -> Bool
Implicit Main
Top-level statements are allowed without wrapping them in fn main(). The compiler synthesizes a main function automatically.