Lambda - Haxe - The Cross-platform Toolkit (original) (raw)

10.5 Lambda

Define: Lambda

Lambda is a functional language concept within Haxe that allows you to apply a function to a list or iterators. The Lambda class is a collection of functional methods in order to use functional-style programming with Haxe.

It is ideally used with using Lambda (see Static Extension) and then acts as an extension to Iterable types.

On static platforms, working with the Iterable structure might be slower than performing the operations directly on known types, such as Array and List.

Lambda Functions

The Lambda class allows us to operate on an entire Iterable at once. This is often preferable to looping routines since it is less error-prone and easier to read. For convenience, the Array and List class contains some of the frequently used methods from the Lambda class.

It is helpful to look at an example. The exists function is specified as:

static function exists( it : Iterable, f : A -> Bool ) : Bool

Most Lambda functions are called in similar ways. The first argument for all of the Lambda functions is the Iterable on which to operate. Many also take a function as an argument.

This example demonstrates the Lambda filter and map on a set of strings:

using Lambda; class Main { static function main() { var words = ['car', 'boat', 'cat', 'frog'];

    var isThreeLetters = function(word) return word.length == 3;
    var capitalize = function(word) return word.toUpperCase();

    // Three letter words and capitalized. 
    trace(words.filter(isThreeLetters).map(capitalize)); // [CAR,CAT]
}

}

This example demonstrates the Lambda count, has, foreach and fold function on a set of ints.

using Lambda; class Main { static function main() { var numbers = [1, 3, 5, 6, 7, 8];

    trace(numbers.count()); // 6
    trace(numbers.has(4)); // false

    // test if all numbers are greater/smaller than 20
    trace(numbers.foreach(function(v) return v < 20)); // true
    trace(numbers.foreach(function(v) return v > 20)); // false

    // sum all the numbers
    var sum = function(num, total) return total += num;
    trace(numbers.fold(sum, 0)); // 30

    // get highest number
    trace(numbers.fold(Math.max, numbers[0])); // 8
    // get lowest number
    trace(numbers.fold(Math.min, numbers[0])); // 1
}

}