callback and _


In older versions (2.8 and prior), currying was applied with the callback function. callback creates a wrapper function around another function, automatically inserting arguments into the original function that will persist every time the wrapper function is called.

public function foo(x:Int, y:Int) {return x+y;}

public static function main(){
    // creates a copy of foo() that automatically makes the first argument a 4
    var foo_cb = callback(foo,4);
    trace(foo_cb(5)); // traces 9

Callback is similar to what you can accomplish through some of the methods in the Reflect API. However, with callback you can only insert arguments in order (i.e. you must specify the first argument before you can specify the second argument, and so forth). In this way, callback was more limited than any of the Reflect methods, but the new 3.0 syntax is more flexible.


The big advantage of using callback (or the new syntax) is that it is a fully typed call, for both arguments and arity, so you get type-safe code (unlike Reflect, which is all Dynamic). This is very useful in functional routine arguments, such as the Lambda methods, which typically require a function that takes only one argument. For example, you can do this:

// calculate the powers of 3 for each element of an array,
// and return the results in a new array:
trace( [10,2,36,4,5], Math.pow(3, _)));

// that is the same as this:
trace( [10,2,36,4,5], callback(Math.pow, 3)));

// which is also the same as this:
trace( [10,2,36,4,5], function(x) { return Math.pow(3, x);}));
version #20113, modified 2014-05-21 13:13:34 by Simn