Skip to content

Function Captures

Functions in Calibre can capture values from the surrounding scope.

This is often called a closure.

Here, scale uses factor even though factor is defined outside the function itself.

const main := fn => {
let factor := 10;
let scale := fn (x : int) -> int => x * factor;
print(scale(3));
};

Closures are especially useful for short callback-style functions.

const main := fn => {
let bonus := 5;
let values := list:<int>[1, 2, 3].into_iter().map(fn (x : int) -> int => x + bonus).collect();
print(values);
};

Closures can also work with mutable values from the surrounding scope.

const main := fn => {
let mut total := 0;
fn => {
total += 1;
}();
print(total);
};

Capturing is part of what makes Calibre’s anonymous functions practical: they can use the local context around them instead of requiring every value to be passed explicitly.