GenerativeComponents Help

Lambda Expressions

Lambda expressions provide an easy and concise way to define an ad-hoc, anonymous function, usually within the context of a larger expression

The syntax for a lambda expression is one of the following:

Syntax Example(s) Equivalent example(s) using "function" syntax
argument => expression
x => x + 1
function (x) { return x + 1; }
argument => { statements }
x => { int y = x + 1;
       int z = y / 2;
       return z; }
function (x)
{
    int y = x + 1;
    int z = y / 2;
    return z;
}
(arguments) => expression
(x, y) => x + y

(int x, y = 5) =>  x + y
function (x, y) { return x + y; }

function (int x, y = 5) { return x + y; }
(arguments) => { statements }
(x, y) => { int z = x + y;
            return z > 5 ? 5 : z; }


(int x, y = 5, out z) => { z = x + y;
                           if (z > 5)
                               z = 5; }
function (x, y)
{
    int z = x + y;
    return z > 5 ? 5 : z;
}

function (int x, y = 5, out z)
{
    z = x + y;
    if (z > 5)
        z = 5;
}

In particular, lambda expressions make it easier to call functions that take other functions as arguments. For example, Nodes is a built-in function that returns all nodes in the GC model:

	Nodes()

The Nodes function takes an optional argument that is, itself, a function that identifies which nodes should be returned. The following expression returns all Point nodes in the GC model:

	Nodes(n => n is Point)

which is equivalent to:

	Nodes(function (n) { return n is Point; })

Furthermore, suppose we want the resultant list to be sorted. The following expression returns all Point nodes in the GC model, sorted by node name:

	Nodes(n => n is Point).Sort((x, y) => x.Name < y.Name)

which is equivalent to:

	Nodes(function (n) { return n is Point; }).Sort(function (x, y) { return x.Name < y.Name; })

Incidentally: In this case, we could, alternatively, use a query expression. The following expression returns all Point nodes in the GC model, sorted by node name:

	from n in Nodes() where n is Point orderby n.Name;
Technical note: Because curly braces
{ ... }
are used to denote both lists and code blocks, the lambda expression
x => {}
is ambiguous: It could be interpreted as returning an empty list, or as having an empty function body. GCScript resolves this ambiguity by interpreting it as returning an empty list. To specify a lambda expression having a "do-nothing" function body, use either of the form
x => {;}
or
x => { return; }