Lambdas / Anonymous functions

Anonymous function

fun(Int x, Int y) -> Int {
    x + y
}


numbers.map(fun(x) {
    x * 2
})thp
    
Syntax error: Expected an identifier after the `fun` keyword. at line 1:3

Closure types

By default closures always capture variables as references.

var x = 20

val f = fun() {
    print(x)
}

f()     // 20

x = 30
f()     // 30thp
    
Syntax error: Expected an expression after the equal `=` operator at line 3:7

You can force a closure to capture variables by value.

fun(parameters) clone(variables) {
    // code
}thp
    
Syntax error: Expected an identifier after the `fun` keyword. at line 1:3
var x = 20

val f = fun() clone(x) {
    print(x)
}

f()     // 20

x = 30
f()     // 20thp
    
Syntax error: Expected an expression after the equal `=` operator at line 3:7

Lambdas

Lambdas are a short form of anonymous functions. They are declared with #{}.

Inside the lambda you can access the parameters as $1, $2, etc.

Finally, lambdas be written outside of the parenthesis of function calls.

numbers.map() #{
    $1 * 2
}

// the above lambda is equivalent to:

numbers.map(fun(param1) {
    $1 * 2
})thp
    
Syntax error: Unexpected token `.`, expected a new line at line 1:7