Functions

Declaration

fun name(param1, param2) {
    // body
    return value;
}

Functions are first-class values. They can be stored in variables, passed as arguments, and returned from other functions.

fun add(a, b) {
    return a + b;
}
print add(2, 3);          // 5

Return

The return statement exits the function and produces a value. If omitted, the function returns nil.

fun greet(name) {
    return "Hello, " + name + "!";
}
print greet("Mac");       // Hello, Mac!

Implicit Return

The last expression in a function body, when written without a trailing semicolon, becomes the return value of the function.

fun add(a, b) {
    a + b
}
// equivalent to: fun add(a, b) { return a + b; }

A trailing semicolon suppresses the implicit return -- the function returns nil instead:

fun f() { 42; }
print f();                // nil

Explicit return statements still work as before and take precedence.

Closures

Functions capture variables from their enclosing scope.

fun makeCounter() {
    var count = 0;
    fun increment() {
        count = count + 1;
        return count;
    }
    return increment;
}

var counter = makeCounter();
print counter();              // 1
print counter();              // 2

Functions as Values

fun apply(f, x) {
    return f(x);
}

fun double(n) { return n * 2; }

print apply(double, 5);      // 10

Recursion

Functions can call themselves.

fun factorial(n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}
print factorial(5);           // 120

See Also