Skip to content

Instantly share code, notes, and snippets.

@fponticelli
Last active December 14, 2015 06:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fponticelli/5040330 to your computer and use it in GitHub Desktop.
Save fponticelli/5040330 to your computer and use it in GitHub Desktop.
Function wrapping in abstract
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