If f :: (a, b) -> c, we can define curry(f) as below:
curry(f) :: ((a, b) -> c) -> a -> b -> c
const curry = f => a => b => f(a, b);
const sum = curry((num1, num2) => num1 + num2);
console.log(sum(2)(3)); //5
How do we implement generic curry function that takes a function with n parameters?
Caveat: I don't have a functional background, so my terminology may be a bit off.
If by "curry" you mean "create a new function that will call the original with some arguments pre-filled," the general solution in ES5 and earlier is as follows (see comments):
In ES2015+, we can use rest args instead of
arguments
:ES6/2015
ES5
If I understand correctly, I think this is the way to go using ES6:
If you want to do this in ES5, here's a slightly more verbose method:
Below is a solution inspired by Juan Sebastián Gaitán's solution I have just extended it for below cases:
As the output is a function, you need valueOf(). to get the value. the function looks little cumbersome because of .reduce() but its very simple to read.
This is a good example of recursive function and a currying function.
There's a simple way to curry your
sum
function with unlimited parameters.This
add
function would run every time you call the curried function with another parameter. Like in the case forconst six = four + two;
It returns the value from two previous calls and the chain goes on and on.Keep in mind that in order to get the primitive value we need to call
.valueOf()
.