Skip to content
Plumlang

Language reference · Section 6

Functions

6.1 Declaring and calling

branch add(a: int, b: int) -> int {
    return a + b
}

branch greet(name: str) {           # returns none
    drop("Hello, {name}")
}

drop(add(2, 3))
greet("Ada")

Parameter types are always written. The result type is written after -> and left out for functions that return nothing. A function whose result is not none must return a value on every path; the compiler checks.

A function body that is a single expression can use =>:

branch square(x: int) -> int => x * x

Functions can be called before their declaration in the same module. A function may use module variables declared anywhere in the module, but using one before its plant or root line has run (a call made above the declaration) is a runtime Error, not a value of the wrong type:

branch greet() -> str => "Hello, {name}"
drop(greet())        # Error: a module variable was used before its `plant` line ran
plant name = "Ada"
drop(greet())        # Hello, Ada

Using a module variable above its declaration outside a function is a compile error (E0303).

6.2 Default and named arguments

branch connect(host: str, port: int = 80, secure: bool = bad) { }

connect("example.com")
connect("example.com", 443, secure: good)
connect("example.com", secure: good)

Defaults must be constants or literals. Named arguments come after positional ones.

6.3 Parameters are read-only

Parameters are constants inside the function. Because strings, lists and maps are values (section 11), a function cannot change the caller's list; it returns a new one, or takes a tree, whose objects are shared.

6.4 Function values and closures

Functions are values. A lambda is written (params) => expression or (params) => { statements }:

plant double = (x: int) => x * 2
plant evens = numbers.filter((n) => n % 2 == 0)
plant sorted = people.sorted_by((p) => p.age)

Lambda parameter types can be left out when the context gives them, as in filter above. A lambda captures the variables it uses; it sees their current values (a captured plant can be changed by the lambda only if it is declared in an enclosing function, not across tasks).

6.5 Recursion

Functions may call themselves. Deep recursion past the stack limit (by default 10,000 frames) is a runtime error, not a crash. Calls made from inside the runtime (a to_str running while something prints, the function given to map or filter) may nest 100 deep; past that is also a runtime error.