Lambdas / Anonymous functions

Anonymous function

An anonymous function is declared with fn. Other than not having a name, it can declare parameter and return types.

fn(Int x, Int y) -> Int {
  x + y
}thp

Anonymous function can omit declaring those types as well:

numbers.map(fun(x) {
  x * 2
})thp

Anonymous function short form

If you need an anonymous function that returns a single expression you can write it like this:

fun(x, y) = x + ythp

It uses an equal = instead of an arrow. It can contain only a single expression.

This is common when declaring functions that immediately return a map.

fn(value) = .{
  value
}thp

Closure types

By default closures always capture variables as references.

var x = 20

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

f() // 20

x = 30
f() // 30thp

You can force a closure to capture variables by value.

fun(parameters) clone(variables) {
  // code
}thp
var x = 20

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

f() // 20

x = 30
f() // 20thp

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