Functions and lambdas
Use case: named helpers
Section titled “Use case: named helpers”fn double(x: int) -> int { return x * 2}
fn main(caps: Caps) -> int { return double(21)}Return type is required on functions. Function bodies need an explicit return (trailing bare expressions are for block/match arms, not whole functions).
Use case: pass a function value
Section titled “Use case: pass a function value”fn double(x: int) -> int { return x * 2}
fn is_even(x: int) -> bool { return x % 2 == 0}
fn main(caps: Caps) -> int { let xs = [1, 2, 3, 4] let ys = array_map(xs, double) let evens = array_filter(xs, is_even) print ys print evens return len(evens)}Use case: inline lambdas
Section titled “Use case: inline lambdas”Paren lambdas only — not |x| …:
fn main(caps: Caps) -> int { let xs = [1, 2, 3, 4] let zs = array_map(xs, (x: int) -> x * 3) let evens = array_filter(xs, (x) -> x % 2 == 0) print zs print evens return 0}| Form | Status |
|---|---|
(x: int) -> expr |
Works |
(x) -> expr |
Works (types inferred where possible) |
|x| expr |
Rejected — use paren form |
Methods on structs
Section titled “Methods on structs”Receiver is an explicit self parameter:
struct User { name: String fn greet(self) -> String { return "hello " + self.name }}
fn main(caps: Caps) -> int { let u = User { name: "Ada" } print u.greet() return 0}Methods use fn, not function.
Type aliases
Section titled “Type aliases”type Score = int
fn bump(s: Score) -> Score { return s + 1}