I'm trying to create curry function that can be applied to any function and return another, with 1 of the arguments applied. Properties that I want to have:
- If function has only one argument curry function should return value: f(a); curry(f,x) = f(x);
- If function has many arguments currey should retrun curried function: g(a1,a2,..,aN); curry(g,x) = g2(a2,..,aN) : g2(a2,..aN)=g(x,a2,...,aN)
- Length propery of curried function should work "as needed" g.length = N => curry(g,x).length = N-1
There is some implementations of curry in Prototype Framework and discussion in one blog. But this implementation is not good because it doesn't work well on functions with only one argument (1), and also returning function 'length' attribute is 0 (3).
For first property there is an easy implementation:
function curry(f,x) {
if (f.length == 1) return f(x);
...
}
But I don't know how to work with 3rd rule, i.e. function can be constucted as inner function since there will be a nested Lexical Environment and will be able to use f:
function curry(f,x) {
return function() { ... }
}
but in this case I'll no longer will able to explicitly set parameters. On the other hand function can be constructed with 'new Function' statement, smth like that:
function curry(f,x) {
var args = [];
for (var i=1; i<f.length; i++) {
args.push('a'+i);
}
var sa = args.join();
return new Function(sa,"return f(x,"+sa+")");
}
But in this situation f and x will unbound because anonymous function will be created in Global Lexical Environment.
So the questions:
- is there a way to explicitly set parameters count when creating function with function keyword?
- is there a way to set Environment of function created with 'new Function' statement?
- us there a way to solve my problem in any other way?