Last active
December 14, 2015 06:09
-
-
Save fponticelli/5040330 to your computer and use it in GitHub Desktop.
Function wrapping in abstract
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract FunctionInfo<T>({ f : T, arity : Int, hasReturn : Bool }) | |
{ | |
public inline function new(f : T, arity : Int, hasReturn : Bool) | |
{ | |
this = { f : f, arity : arity, hasReturn : hasReturn }; | |
} | |
public inline function self() : T return this.f; | |
public inline function call(args : Array<Dynamic>) | |
{ | |
return Reflect.callMethod(null, this.f, args); | |
} | |
@:to public inline function toFunction0<TR>() : Void -> TR | |
{ | |
if(this.arity != 0) throw "wrong arity"; | |
return cast this.f; | |
} | |
@:from public static inline function fromFunction0<TR>(p : Void -> TR) | |
{ | |
return new FunctionInfo(p, 0, true); | |
} | |
@:to public inline function toProcedure1<T1>() : T1 -> Void | |
{ | |
if(this.arity != 1) throw "wrong arity"; | |
return cast this.f; | |
} | |
@:from public static inline function fromProcedure1<T1>(p : T1 -> Void) | |
{ | |
return new FunctionInfo(p, 1, false); | |
} | |
} | |
class TestFunctions | |
{ | |
public function new() { } | |
public function testAnyFunction() | |
{ | |
var info : FunctionInfo<Void -> Bool> = function() return true; | |
Assert.isTrue(info.call([])); | |
var f : Void -> Bool = info; | |
Assert.isTrue(f()); | |
Assert.isTrue(info.self()()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment