Sometimes one would like to create a closure directly, without bothering to give it a name.
There is a special keyword lambda
for this purpose. By writing a
function definition without the keyword def
and replacing the function name with
the keyword lambda
, that definition becomes an expression which publishes a closure.
Note that a lambda
cannot create a recursive function, since the function is
not given a name in the body.
{- Define a function that sums the results of its argument function evaluated with arguments 1 and 2 -} def onetwosum(f) = f(1) + f(2) onetwosum( lambda(x) = x * 3 ) {- identical to: def triple(x) = x * 3 onetwosum(triple) -} {- OUTPUT: 9 -}
The type of a lambda
expression is exactly the type of the closure it creates.
Related Reference Topics
Related Tutorial Sections