patternjavascriptMinor
A curry function
Viewed 0 times
curryfunctionstackoverflow
Problem
I am new to the functional style, and I wrote a curry function to practice this new style. This curry function takes a regular function and returns the curried version of it. Currying is a technique, with which you can partially evaluate functions.
function curry(f, self) {
return function () {
if (arguments.length == f.length) {
return f.apply(self, arguments);
}
arguments = Array.prototype.slice.call(arguments);
return curry(f.bind.apply(f, [self].concat(arguments)));
}
}
function f(a, b, c, d) {
return this + a + b + c + d;
}
document.write("f(1, 2, 3, 4) = ", curry(f, 0)(1, 2, 3, 4), "
");
document.write("f(1, 2, 3)(4) = ", curry(f, 0)(1, 2, 3)(4), "
");
document.write("f(1)(2, 3, 4) = ", curry(f, 0)(1)(2, 3, 4), "
");
document.write("f(1)(2)(3)(4) = ", curry(f, 0)(1)(2)(3)(4), "
");Solution
Interesting question,
your code is very close to the code here : http://blog.carbonfive.com/2015/01/14/gettin-freaky-functional-wcurried-javascript/
I prefer your lack of
I would name the anonymous function, anything is better than 'anonymous function' when debugging.
your code is very close to the code here : http://blog.carbonfive.com/2015/01/14/gettin-freaky-functional-wcurried-javascript/
I prefer your lack of
else since your if block has a return anyway.I would name the anonymous function, anything is better than 'anonymous function' when debugging.
function curry(f, self) {
return function curriedFunction() {
if (arguments.length == f.length) {
return f.apply(self, arguments);
}
arguments = Array.prototype.slice.call(arguments);
return curry(f.bind.apply(f, [self].concat(arguments)));
}
}Code Snippets
function curry(f, self) {
return function curriedFunction() {
if (arguments.length == f.length) {
return f.apply(self, arguments);
}
arguments = Array.prototype.slice.call(arguments);
return curry(f.bind.apply(f, [self].concat(arguments)));
}
}Context
StackExchange Code Review Q#121786, answer score: 4
Revisions (0)
No revisions yet.