# 4. Functions ```rex func add(a: int, b: int): int { return a + b } func greet(name: string) { // no result: nothing after the parentheses print("hi", name) } func main() { print(add(2, 3)) greet("Ada") } ``` ```text 5 hi Ada ``` Names in a row can share a type: `func area(w, h: float): float`. ## Several results A function can return more than one value. The most common use is a value and an `error`. ```rex func divide(a, b: int): (int, error) { if b == 0 { return 0, error("cannot divide by zero") } return a / b, nil } func main() { var q, err = divide(7, 2) print(q, err) var _, err2 = divide(1, 0) print(err2) } ``` ```text 3 nil cannot divide by zero ``` More in [Errors and nil](07-errors-and-nil.md). ## Parameters are safe A parameter is a copy as far as you can tell: changing it inside never changes the caller's variable. (When a function only *reads* a parameter, the compiler passes it without copying, so big lists are free to pass around.) ```rex func grow(xs: []int): []int { xs.push(99) return xs } func main() { var a = [1, 2] var b = grow(a) print(a, b) } ``` ```text [1, 2] [1, 2, 99] ``` ## Functions are values A function has a type like `func(int): int`. You can store it, pass it and return it. ```rex func double(x: int): int { return x * 2 } func apply(f: func(int): int, x: int): int { return f(x) } func main() { print(apply(double, 4)) var triple = func(x: int): int { return x * 3 } print(apply(triple, 4)) print(apply(x => x + 1, 4)) // short form } ``` ```text 8 12 5 ``` ### Short lambdas `x => x * 2` and `(a, b) => a + b` are shorthand for a one-expression function. The types come from where it is used, so it works where Rex already knows what function is expected (a parameter, a typed variable, a struct field, or another argument of a generic function). The short form is one expression; for several statements use the long `func(x: int): int { }`. ### Closures remember A function written inside another can use the variables around it. It **copies** them when it is created and keeps its own copy from then on. ```rex func make_counter(): func(): int { var n = 0 return func(): int { n += 1 return n } } func main() { var next = make_counter() print(next(), next(), next()) var offset = 10 var add = func(x: int): int { return x + offset } offset = 99 // the closure keeps its own 10 print(add(1)) } ``` ```text 1 2 3 11 ``` ## `defer`: clean up at the end `defer` puts a line aside and runs it when the block it is in ends, however it ends: at the closing `}`, at a `return`, at a `?` that passes an error up, or at `break` / `continue` in a loop. Use it to keep the cleanup right next to the thing that needs it. ```rex func process(name: string): error { print("open", name) defer print("close", name) // runs last, whatever happens below if name.ends_with(".tmp") { return error("{name}: skipped") } print("work on", name) return nil } func main() { var err = process("a.txt") err = process("b.tmp") print(err) } ``` ```text open a.txt work on a.txt close a.txt open b.tmp close b.tmp b.tmp: skipped ``` - Several `defer`s run in reverse: the last one written runs first (close in the opposite order you opened). - `defer { ... }` runs a whole block. - The deferred code sees the variables as they are **when it runs**, not when `defer` was written. - In a loop body, it runs at the end of every round. - `return`, `?` and `break` can't be used inside the deferred code itself: it runs while the block is already finishing. - It is most useful with things you must close by hand, like files from C libraries: ```rex var f = stdio.fopen(path, "r") if f == nil { return error("can't open {path}") } defer stdio.fclose(f) ``` Next: [Lists and maps](05-lists-and-maps.md)