Skip to content

Closure

Bill Hails edited this page Mar 31, 2024 · 3 revisions

Functions are closures that capture their lexical environment and are first class. They can be passed around like any other variable. For example:

let
    fn adder(x) {
        fn (y) { x + y }
    }
in
    add2 = adder(2);
    add3 = adder(3);

    add2(3); // 5
    add3(3); // 6

The inner anonymous function returned by adder captures the argument value of x and when later invoked adds that to its argument y.

Next: Currying

Clone this wiki locally