14

In the Haxe programming language, is it possible to pass a function as a parameter (like in JavaScript?)

For example, is the following code considered valid in Haxe?

function a(){
    trace("This function is being used as a parameter!");
}

function b(theFunction){
    theFunction();
}

b(a); //is this equivalent to a(); ?
Anderson Green
  • 30,230
  • 67
  • 195
  • 328
  • I don't know about haxe: but in `b(a)` you substituted the name of a function with its definition. These are almost always the same. I say almost always because if haxe tries to do something funny to the function argument (say `a` had a parameter and, upon passing it as an argument the semantics of haxe enforced the argument to be reduced to some normal form...you may end up with non-termination. As it stands I can't think of any difference – user1666959 Dec 24 '12 at 22:19
  • @user1666959 Not all languages allow passing functions as arguments - Java, for example, doesn't allow functions to be passed as arguments. Is it possible in Haxe, or is it not possible? – Anderson Green Dec 24 '12 at 22:25

2 Answers2

17

It is definitely possible, and is a pattern used in the standard library, especially in the Lambda class:

class Test {
  static function main(){
    var arr = [0,1,2,3,4,5,6,7,8,9,10];
    var newArr = Lambda.filter(arr, function (num) { 
      return num % 2 == 0; 
    });
    for (i in newArr)
    {
      trace (i);
    }
  }
}

(See http://try.haxe.org/#C9dF3)

To define your own methods that take functions as parameters you use the (param1Type)->(param2Type)->(returnType) syntax:

function test1(myFn:String->Void) { myFn("hi"); }
test1(function (str) { trace(str); });

function test2(myFn:String->String) { var newStr = myFn("hi"); }
test2(function (str) { return str.toUpperCase(); });

function test3(myFn:Int->String->Array<Int>->Void) { myFn(3, "Jason", [1,2,3,4]); }
test3(function(num:Int, name:String, items:Array<Int>) { ... });
Jason O'Neil
  • 5,908
  • 2
  • 27
  • 26
9

See and try for yourself please:)

http://try.haxe.org/#CFBb3

Andy Li
  • 5,894
  • 6
  • 37
  • 47
  • Thanks - I forgot that it was possible to test Haxe code online. :) – Anderson Green Dec 25 '12 at 00:47
  • The other really quick way to test things is by compiling to neko... you just use "haxe -x MyTestClass.hx" and it will generate "MyTestClass.hx.n" and run it for you all at once. Really handy for quickly checking how something works in Haxe. – Jason O'Neil Dec 25 '12 at 08:21