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), "<br>");
document.write("f(1, 2, 3)(4) = ", curry(f, 0)(1, 2, 3)(4), "<br>");
document.write("f(1)(2, 3, 4) = ", curry(f, 0)(1)(2, 3, 4), "<br>");
document.write("f(1)(2)(3)(4) = ", curry(f, 0)(1)(2)(3)(4), "<br>");
self
argument used for? Can't you usethis
if it's not defined? (and allow something likecurry(f)(0)
. \$\endgroup\$0
? That's not quite equivalent. \$\endgroup\$