Typing functions in haXe
Hello everyone,
There’s been an interesting question on the haXe’s mailing-list regarding typing of functions. No matter what the question really was, it made me think I should write something about functions typing in haXe because it may not be really obvious when you’re not used to it.
So, Functions are typed.
Yes, functions are, like any other object, typed. Their type depends on two thing :
- The arguments taken by the function
- The return type of the function (the type of the object that’s going to be returned)
So a function written like this :
public function m1(arg1 : String, arg2 : String) : Int
would be typed as taking as first parameter a String, as second parameter a String, and returning an Int. We note this like that :
String->String->Int
More fun.
What’s even funnier, is that a function can take a function as a parameter, it can also return a function. So, how would we write that? It’s easy, just put parenthesis around things! Now, let’s imagine a function m1 that wants as first parameter a String, as second argument a function taking a String and returning an Int, and that returns an Int. We would write it like that :
function m1(arg1 : String, arg2 : String->Int) : Int;
And this would be typed as :
String->(String->Int)->Int.
Imagine m2, which takes the same parameters as m1 but returns a function taking an Int, an Int and returning a String. We could write it like this :
function m2(arg1 : String, arg2 : String->Int) : Int->Int->String;
This would be typed as :
String->(String->Int)->(Int->Int->String)
And you can embed things more and more… but pay attention to the parenthesis! ;)