Files
rexlang/docs/04-functions.md
T
Your NameandClaude Opus 5.5 7cf9727bcd Rename the language from Dino to Rex
Files use .rex, the command is rex, and the crate, runtime prefixes,
docs, editor files and examples all use the new name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 13:51:23 +01:00

133 lines
2.5 KiB
Markdown

# 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
```
Next: [Lists and maps](05-lists-and-maps.md)