Functions & Control Flow

Function Declarations

// Full declaration with types
fn add(a: Int, b: Int) -> Int {
    return a + b
}

// Short syntax for single-expression functions
fn square(x: Int) = x * x

// With type inference
fn greet(name) = "Hello, " + name

Lambdas / Closures

let add = fn(a, b) -> a + b
let inc = |x| x + 1

// Multi-line lambda
let compute = |x| {
    let y = x * 2
    return y + 1
}

// Higher-order function
fn apply(f: fn(Int) -> Int, x: Int) -> Int { f(x) }
let result = apply(|n| n * n, 5)  // 25

Conditionals

if x > 0 {
    print("positive")
} else if x == 0 {
    print("zero")
} else {
    print("negative")
}

Pattern Matching

match value {
    Option.Some(v) if v > 0 => process(v),
    Option.Some(v) => log("zero or negative"),
    Option.None => log("nothing"),
}

Loops

// While loop
let mut i = 0
while i < 5 {
    print(i)
    i += 1
}

// For-in loop over ranges
for i in 0..5 {
    print(i)
}

// For-in loop over collections
let items = [10, 20, 30]
for item in items {
    print(item)
}

Early Returns

fn find_user(id: Int) -> Option<String> {
    if id < 0 { return Option.None }
    // ...
    Option.Some("user")
}

Method Syntax

impl Point {
    fn translate(self: &mut Point, dx: Int, dy: Int) {
        self.x += dx
        self.y += dy
    }
}

let mut p = Point{ x: 0, y: 0 }
p.translate(5, 10)