Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Functions as values

A function is a value like any other. You can put it in a variable, hand it to another function, or keep it in a map.

Writing one where you need it

=> makes a function out of one expression: what goes in on the left, what comes back on the right.

square = n => n * n
add = (a, b) => a + b
PRINT square(7), add(2, 3)
49 5

Mostly you’ll write them right where another function wants one.

FUNCTION keep(list, wanted)
    LOCAL kept = []
    FOR item = list
        IF wanted(item) THEN PUSH kept, item
    END FOR
    RETURN kept
END FUNCTION

FUNCTION change(list, how)
    LOCAL changed = []
    FOR item = list
        PUSH changed, how(item)
    END FOR
    RETURN changed
END FUNCTION

numbers = [1, 2, 3, 4, 5, 6]
PRINT keep(numbers, n => n MOD 2 = 0)
PRINT change(numbers, n => n * 10)

keep(numbers, n => n > 2)
    ## change(_, n => n * n)
    ## PRINT _
[2, 4, 6]
[10, 20, 30, 40, 50, 60]
[9, 16, 25, 36]

When one line isn’t enough

A FUNCTION with no name is the long form. It ends with END FUNCTION like any other.

FUNCTION change(list, how)
    LOCAL changed = []
    FOR item = list
        PUSH changed, how(item)
    END FOR
    RETURN changed
END FUNCTION

labels = change([3, 50, 700], FUNCTION(n)
    IF n < 10 THEN RETURN "small"
    IF n < 100 THEN RETURN "medium"
    RETURN "huge"
END FUNCTION)
PRINT labels
[small, medium, huge]

What it remembers

A function written inside another keeps a copy of the locals around it, as they were when it was made.

FUNCTION multiplier(factor)
    RETURN n => n * factor
END FUNCTION

double = multiplier(2)
triple = multiplier(3)
PRINT double(10), triple(10)

tools = {twice: double, thrice: triple}
PRINT tools.thrice(5)
20 30
15

From Python: n => n * 2 is your lambda n: n * 2, and the long form is a def you didn’t have to name.

From JavaScript: The same arrows you know. One difference: a function gets a copy of the locals around it. Changing its copy doesn’t change the original, so there’s no counter hiding in a closure. Use a map or a shared variable for that.

From Lua: Same as your function(n) ... end, with the copying rule above where you have upvalues.

From BASIC: This is the thing you used to need GOSUB tricks or a string with a function’s name in it to fake.