GenerativeComponents Help

Anonymous Functions

Every function is a kind of object, which (therefore) can be assigned to a variable, passed as an argument to a method call, or returned as the result of another function. Furthermore, like a number or a string, a new function can appear spontaneously within an expression or statement, without needing an associated name. These "ad hoc" functions are called anonymous functions.

To create an anonymous function, we use the keyword function instead of a name. Also, it's conventional to omit the types of the return value and the arguments, but you're welcome to include those types if you prefer.

For example:

	double Plus(int x, int y) { return x + y; } 
// A named function that, when called, will add two numbers.
	function(x, y) { return x+ y; }  // An anonymous
function that, when called, will add two numbers.

As an example of when and how to use an anonymous function, following is a code snippet that calls the 'Select' method. That method can be applied to any list, and returns a new list comprised of only those members that satisfy a certain condition. The condition is specified by passing a function, which typically is an anonymous function:

	int[] source = {9, 3, 6, 34, 2, 10};
	int[] largeValues = source.Select(function(x) { return
x > 8; });  // Anonymous function passed as argument.
	// Now the value of 'largeValues' is {9, 34, 10}.

It is sometimes useful to create an anonymous function and then immediately call it within the same expression. For example:

	int n = 5;
	int[] squares = function(limit) { int[] result = {};
for (int i = 0; i < limit; ++i) result.Add(i * i); return result;
} (n);
	// Note the text '(n)' following the anonymous function;
this denotes that we're calling the anonymous function
	// with the argument, n.
	// Now the value of 'squares' is {0, 1, 4, 9, 16}.

As an alternative to defining a named function, we can define an anonymous function, assign it to a variable, and subsequently use that variable to call the function. For example:

	function Plus = function(x, y) { return x + y; }
	int sum = Plus(3, 4);

You might be interested to know that, from the standpoint of the GCScript compiler, the following two statements are identical:

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