A Tour of Morfa

Function literals

A function literal may be used to construct a functional value (that is, a value of a function type) without writing a complete function declaration. In some programming languages, function literals are called lambda expressions, by analogy with the λ-calculus.

Here a function literal is assigned to a variable square:

unittest
{
    var square = func(n: int): int { return n * n; };
    assert (square(5) == 25);
}

As with function declarations, if the return type is omitted the compiler will try to infer it from the function body. You may also omit the leading func for brevity.

unittest
{
    var cube = (n: int) { return n * n * n; };
    assert (cube(5) == 125);
}

However, either func or the return type has to present if the function takes no arguments.

A typical use of a function literal is for constructing function values to be passed as arguments to higher order functions. As an example consider the following function transform that applies a given function f to every element of a given array a of integers, and its example invocation with a function literal as a second argument:

import morfa.util.Range;
func transform(a: int[], f: func(int): int): void
{
    for (i in range(a.length))
        a[i] = f(a[i]);
}

unittest
{
    var a = [1,2,3,4];
    transform(a, (n: int) { return n * n; });
    assert (a == [1,4,9,16]);
}