Generic function type that would support all kinds of argument counts

During the recent years, I’ve came many times to deadends when I tried to a pass a function as a parameter retun a modified but I wanted to be generic to anything callable, regardless of argument count.

Examples are memoization, debouncing, throttling, do while waiting, etc.

Of course there are workaround like using and (T)->T and use a anon object as T, or the C++ way of creating a class with an invoke method that takes no parameters.

In many cases this is not pretty, and also sometimes I do not have control over the functions, and on the environments that would use the functions.

Is there any solution for that?

function expensive(a:Int,b:Int,c:Int,d:Int):Int{

}

function veryexpensive(a:BigInt,b:BigInt):Int{

}

function memoize<T>(func:Callable):T{
 var cache=Map<Params,Return>()
return function(...){
if cash.has
else func(...) store in cache.
}
}

var expensive_memoized=memoize(expensive);
var vem=memoize(very_expensive);

In javascript we would use arguments and apply.

In CPP there are solutions c++ - Writing Universal memoization function in C++11 - Stack Overflow however I guess templates are less restircted, and I am not sure that generic supports rest.

  • You can pass an array of arguments to Reflect.callMethod().
  • If the arguments aren’t going to change (like in the case of debouncing), you can use func.bind(arg0, arg1, etc).
  • Your memoize function could be rewritten as a macro, using Context.typeof(func) to get the argument types and macro func($a{ args }) to call the function. Plus several steps in between, which I’m leaving out for brevity. It would end up being faster and more type-safe than Reflect.callMethod(), but I doubt it’d be worth the sheer amount of effort.