Lambdas
Lambdas
A lambda is a value wrapping a function and its closure.
This is useful to be able to customize a function by passing in behaviors and not just values.
For example, filter
can filter a collection by any arbitrary predicate.
A lambda value is created using the =>
syntax.
There is a subscript
function for calling lambdas, called like f[x]
.
The syntax void data(x nat)
defines a lambda type.
The lambda returns void
and takes a nat
.
The parameter name x
is just for documentation.
data
will be explained in the section on Closures.
Parameter destructuring
All lambdas take one parameter, but it can be a tuple.
The syntax makes it look like there are multiple parameters. To show that it's really only one parameter:
Similarly, a lambda can appear to take no parameter, but it actually takes void
.
Closures
The code inside the lambda body (after the =>
)
can access variables outside.
Those variables are called its closure.
Closure purity
The data
keyword is the purity of the closure.
To allow the closure to include shared
or mut
data,
use that keyword in the lambda type instead of data
.
Most ordinary functions in the standard library allow a mut
closure.
Multi-line lambdas
If a lambda's body is long, you can put it in an indented block.
Since this is only possible for the last argument to a funciton, most functions make sure a lambda argument comes last.
Lambdas in records
If a record has a lambda field, it generates a "caller" that gets the lambda and calls it.
(It also generates a getter as usual.)