Return to homepage

DOSATO

Copyright © 2024 Sebastiaan Heins

1.13 Anonymous functions

Arrow functions

Arrow functions are a way to define functions without a name.
They are useful for short functions that are only used once.
Or functions that are passed as arguments to other functions.
Or capturing values from the surrounding scope (closure).

Example of an arrow function:

make myadder = int (int a, int b) => {
    return a + b
}
do sayln(myadder(1, 2)) // 3

The syntax for an arrow function is step-by-step:

1. The type first, this is the return type of the function.
2. Then the arguments of the function, these are enclosed in parentheses.
3. Then the arrow => operator.
4. Then the body of the function, this is enclosed in curly braces.

The arrow function above is a function that takes two arguments a and b and returns their sum.
The function is then assigned to the variable myadder and called with the arguments 1 and 2.
The result is then printed to the console.

Closures

Arrow functions can capture values from the surrounding scope.
This is called a closure.
Example of a closure:

make myadder = null
do { // inside a local scope
    make int a = 1
    set myadder = int (int b) => {
        return a + b
    }
}
do sayln(myadder(2)) // 3

The variable a is defined outside of the arrow function.
The arrow function captures the value of a and uses it inside of the function.
The arrow function is then assigned to the variable myadder and called with the argument 2.
The result is then printed to the console.

Info!
The variable a in this example is saved in the closure of the arrow function.
The block it was in doesn't exist anymore, but the arrow function still has access to the variable a.

Function factory

Arrow functions can be used to create functions dynamically and return them from other functions.
This is called a function factory.
Example of a function factory:

define function makeAdder(int a) {
    return int (int b) => {
        return a + b
    }
}
make myadder = makeAdder(10)
make myadder2 = makeAdder(20)
do sayln(myadder(2)) // 12
do sayln(myadder2(2)) // 22

Each time the function makeAdder is called, it creates a new arrow function that adds the argument a to the argument b.
Each instance has it's own closure, so the value of a is different for each instance.