The aim here is to try and utilize functional programming associativity.
Can bailFirst and bailLast have better names?
I think bailFirst kind of looks like a sum type and bailLast looks like a product type.
update based on #Bergi comment - They return a sum data type of true and string
validate takes a predicate and returns true if valid and the error message if invalid.
bailFirst should stop at the first invalid check
bailLast will run all checks and concatenate the messages into one message.
const validate = (pred, msg) => x => pred(x) ? true : msg;
const bailFirst = (...fns) => x => {
for(let fn of fns) {
const valid = fn(x);
if(valid !== true) return valid;
}
return true;
};
const bailLast = (...fns) => x => {
const msgs = [];
for(let fn of fns) {
const valid = fn(x);
if(valid !== true) msgs.push(valid);
}
if(msgs.length) return msgs.join("\n");
return true;
};
const type = t => validate(x => typeof x === t, `Not a ${t}`);
const str = type('string');
const minLen = min =>
validate(v => v.length > min, `Min length is ${min}`);
const maxLen = max =>
validate(v => v.length < max, `Max length is ${max}`);
const between = (min, max) =>
bailFirst(str, minLen(min), maxLen(max));
const strong = validate(x => /strong_password/.test(x), 'Weak password');
const password = bailLast(str, minLen(8), maxLen(24), strong);
const between2and4 = between(2, 4);
between2and4('foo'); // true
between2and4('foooo'); // Max length is 4
password('abc123'); // Min length is 8\nWeak password
I've often found that difficulty to name something is a sign my abstraction isn't quite right yet. I think the awkwardness here stems from mixing of validation, error aggregation, message formatting, and your boolean | string return types. I agree with bob's recommendation to check out Either and Validation types. If you don't want to reach for a library, you can always use those ideas to help you remodel the problem.
// type Valid :: { valid :: True , messages :: [] }
// type Invalid :: { valid :: False , messages :: [String] }
// type Validation :: Valid | Invalid
// valid :: () -> Valid
const valid = () => validation( true , [] )
// invalid :: [String] -> Invalid
const invalid = messages => validation( false , messages )
// validation :: (Bool, [String]) -> Validation
const validation = ( valid = true , messages = [] ) =>
( { valid , messages } )
// validate :: (a -> Bool, String) -> a -> Validation
const validate = ( predicate , message ) => x =>
predicate( x )
? valid()
: invalid( [ message ] )
// joinValidations :: (Validation, Validation) -> Validation
const joinValidations = ( x , y ) =>
validation( x.valid && y.valid
, x.messages.concat( y.messages ) )
// validateAll :: ...(a -> Validation) -> a -> Validation
const validateAll = ( ...fs ) => x =>
foldMap( validation
, joinValidations
, applyTo( x )
, fs )
// validateSome :: ...(a -> Validation) -> a -> Validation
const validateSome = ( ...fs ) => x =>
foldMapWhile( validation
, joinValidations
, applyTo( x )
, isValid
, fs )
// applyTo :: a -> (a -> b) -> b
const applyTo = x => f => f( x )
// isValid :: Validation -> Bool
const isValid = validation => validation.valid
// foldMap :: Monoid m => (() -> m, (m, m) -> m, a -> m, [a]) -> m
const foldMap = ( mempty , mappend , f , xs ) =>
xs.reduce( ( y , x ) => mappend( y , f( x ) )
, mempty() )
// foldMapWhile :: Monoid m => (() -> m, (m, m) -> m, a -> m, (m, a) -> Bool, [a]) -> m
const foldMapWhile = ( mempty , mappend , f , predicate , xs ) => {
let y = mempty()
for ( const x of xs ) {
if ( !predicate( y , x ) ) return y
y = mappend( y , f( x ) )
}
return y
}
Although appropriate naming is a bit more subjective than Stackoverflow questions usually warrant, I also appreciate the sentiment of wanting to draw the right connections.
bailFirst kind of reminds me of all in Haskell or forall in Scala. Rewriting your js into Haskell would look something like this:
bailFirst :: a -> [a -> Bool] -> Bool
bailFirst x = all ($x)
The fact that it bails early is certainly nice, but doesn't affect the output of the function. So I might call it something related to all.
bailLast however, doesn't actually bail. It seems to return either a boolean or a list of validation errors which is kind of like a stack trace? I might just skip anything fancy call that something like validateAll.
Mind the following function:
function count(n) {
if (n === 0) {
return 0;
} else {
return 1 + count(n - 1);
}
}
It is the simplest recursive function that counts from 0 to N. Since JavaScript has a small stack limit, that function easily overflows. In general, any recursive function can be converted in one that uses a manual stack and, thus, can't stack overflow; but doing so is complex. Is it possible, for the general case, to convert a JavaScript recursive function in one that uses its own stack, without using a continuation-passing style? In other words, suppose we had written:
const count = no_overflow(function(count) {
return function(n) {
if (n === 0) {
return 0;
} else {
return 1 + count(n - 1);
}
}
});
Is it possible to implement no_overflow in such a way that this new count function is equivalent to the old one, except without stack overflows?
Notes:
This is not about tail call optimization, since no_overflow should work for non-tail-recursive functions.
Trampolining is not helpful since, for the general case, it requires the function to be written in a continuation-passing style, which it isn't.
Writing the function with yield doesn't work either for a similar reason: you can't yield from inner lambdas.
That no_overflow would, essentially, work like a stack-free Y-combinator.
In JavaScript, calling a function f(x, y, ...) subjects us to the underlying implementation details of the stack and frames. If you recur using function application, you will absolutely, unavoidably run into a stack overflow.
However, if we can adopt a slightly different notation, such as call(f, x, y, ...), we can control function application however we want -
const add1 = x =>
x + 1
const count = (n = 0) =>
n === 0
? 0
: call(add1, call(count, n - 1)) // <-- count not in tail pos
console.log(noOverflow(count(99999)))
// 99999
Implementing noOverflow is a wrapper around loop, defined in this Q&A -
const noOverflow = t =>
loop(_ => t)
Unsurprisingly this is a non-trivial problem but the answer(s) there should help detail the things you have to consider and some good test cases, should you choose to implement a solution of your own.
Expand the snippet below to verify the results in your browser -
const call = (f, ...values) =>
({ type: call, f, values })
const recur = (...values) =>
({ type: recur, values })
const identity = x =>
x
const loop = (f) =>
{ const aux1 = (expr = {}, k = identity) =>
expr.type === recur
? call (aux, expr.values, values => call (aux1, f (...values), k))
: expr.type === call
? call (aux, expr.values, values => call (aux1, expr.f (...values), k))
: call (k, expr)
const aux = (exprs = [], k) =>
call
( exprs.reduce
( (mr, e) =>
k => call (mr, r => call (aux1, e, x => call (k, [ ...r, x ])))
, k => call (k, [])
)
, k
)
return run (aux1 (f ()))
}
const run = r =>
{ while (r && r.type === call)
r = r.f (...r.values)
return r
}
const noOverflow = t =>
loop(_ => t)
const add1 = x =>
x + 1
const count = (n = 0) =>
n === 0
? 0
: call(add1, call(count, n - 1))
console.log(noOverflow(count(99999)))
// 99999
I stumbled upon this javascript statement:
const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);
I don't understand the expression f(y), x. With some experimenting I found out that this is working too: f(y(x)). It gives the exact same result (for my example at least and is much more understandable to me).
const pipe1 = (...fns) => x => fns.reduce((y, f) => f(y), x);
const pipe2 = (...fns) => x => fns.reduce((y, f) => f(y(x)));
const addThree = x => x + 3;
const addTwo = x => x + 2;
let x1 = pipe1(addTwo, addThree)(2); //x1 is seven
let x2 = pipe2(addTwo, addThree)(2); //x2 is seven
Then I thought that this is some syntax sugar for x,y for x(y) and tried this:
let z = n => addThree, n; //addThree(n)? no, that does not work!
I need some light on the expression f(y), x). Yes I read some stackoverflow articles that the expression is evaluated form left to right and the last is returned. It just makes no sense to me in this example.
fns.reduce((y, f) => f(y), x)
If you format it, it might make more sense.
fns.reduce(
(y, f) => f(y),
x
)
So (y, f) => f(y) is the first parameter to reduce (the reducer function), and x is the 2nd parameter to reduce, which is the initial value.
In conclusion, you were thrown off by the lack of grouping with the arrow function. :)
"Value-X" is going to be the x variable, passed as the 2nd parameter to the reduce function.
const pipe = (...fns) => x => fns.reduce((y, f) => f(y), x);
const foo = pipe(func1, func2, func3);
foo("Value-X");
The expression can be rewritten as this, if it helps to clarify things:
function pipe(...fns) {
return function (x) {
function chain(y, f) {
// y = previous return value
// If this is the first time the function is called, y = x
return f(y);
}
return fns.reduce(chain, x);
}
}
I answered a question yesterday and it got my mind thinking about an interesting (to me) puzzle
With the restriction of using lambdas, numbers, and + only (no if, ?:, or other language features), the goal is to implement some f and some g such that
// contract
f(x) => f'
g(y) => g'
f'(g') == g'(f')
// or more simply:
m(n) == n(m)
Here's what I came up with so far - this code is in JavaScript for the purpose of being able to demonstrate the code in the browser but answers in any functional language are acceptable (racket, clojure, ocaml, lambda calc, etc)
// f
const f = x => k =>
k(y => y + x)
// g
const g = y => k =>
k(x => x + y)
// make instance of each
const a = f(1)
const b = g(2)
console.log(a(b))
// x => x + y1
// should be 3
console.log(b(a))
// y => y + x2
// should be 3
I was able to fix one half of relationship, but the other side remains broken due f and g now being asymmetrical
// f
const f = x => k =>
k(y => y(x))
// g
const g = y => k =>
k(x => x + y)
// make instance of each
const a = f(1)
const b = g(2)
console.log(a(b))
// 3
// should be 3 (OK)
console.log(b(a))
// y => y + x2
// should be 3
I know why it's not working but I'm having trouble trying to fix it. Most importantly, if it's not possible, I'd be interested in learning why.
If you come up with a solution that breaks the restrictions, I'm still interested in seeing it ^_^
This answer assumes a strong non-unit type system (eg. Haskell, but I try to stick to JS-like syntax here).
If we stay in the realm of parametricity, we don't need (and cannot even use) numbers or conditions. The constant functions don't change anything, so I'll leave them out and deal with f and g directly.
First, observe that the equation
f(g) == g(f)
implies that both f and g have function types. Assuming both have different inputs we get that f: A -> X and g: B -> X == (A -> X) -> X == ((B -> X) -> X) -> X == ..., ie., you get an infinite type. I remember having read a paper about this exact construction (one can represent it as a pair of types, and I think it forms a category), but unfortunately forgot its name -- maybe there's more to say here.
A simpler solution would be to require A == B. Then f, g: A -> X, but since X == A by the symmetry equation, it follows that f, g: A -> A -- for arbitrary A, that is. One possibilitity fulfilling this is the identity function:
id(id) == id(id)
The other solutions arise when we specialize A to A -> A; then we search for functions of type (A -> A) -> (A -> A). These are, for one, the (specialized) identity function, which has already been found, but also all functions of the shape h => h o ... o h -- compositions ((o) = h => x => h(h(x))) of a function for a number of types. These "add their repetitions" on application, e.g.
(h => h o h)(h => h o h) == (h => h o h) o (h => h o h)
== h => h o h o h o h.
From this we see that we can choose
f == g == h => h,
f == g == h => h o h,
f == g == h => h o h o h,
f == g == ...
which are, I think, all functions of type forall A. (A -> A) -> (A -> A) (excluding nontermination).
There also seems to be a relation of the limit of this construction (infinite composition) to the infinite case mentined above (now in real Haskell):
Prelude> let g = \h -> h . g
<interactive>:11:19:
Occurs check: cannot construct the infinite type: b ~ (b -> c) -> c
This is the closest I've been able to get but it does use a ternary (?:) expression
const f = x => g =>
g === undefined ? x : g() + x
const g = y => f =>
f === undefined ? y : f() + y
const a = f(1)
const b = g(2)
console.log(a(b)) // 3
console.log(b(a)) // 3
Here f is completely equivalent to g and we could easily just use one or the other
const f = x => g =>
g === undefined ? x : g() + x
const a = f(1)
const b = f(2)
console.log(a(b)) // 3
console.log(b(a)) // 3
For this to happen obviously both f and g has to accept a function as an argument and return a same type value. However after tinkering a while it quickly strike me that i am dealing with infinite types.
Well unless your functions are Haskell's id like JS's x => x. So in Haskell i would do;
f :: a -> a
g :: a -> a
f = id
g = id
*Main> f(g)(+3) 2
5
*Main> g(f)(+3) 2
5
Can simply be implemented in JS as well.
I wrote a simple curry function in JavaScript which works correctly for most cases:
const curry = (f, ...a) => a.length < f.length
? (...b) => curry(f, ...a, ...b)
: f(...a);
const add = curry((a, b, c) => a + b + c);
const add2 = add(2);
const add5 = add2(3);
console.log(add5(5));
However, it doesn't work for the following case:
// length :: [a] -> Number
const length = a => a.length;
// filter :: (a -> Bool) -> [a] -> [a]
const filter = curry((f, a) => a.filter(f));
// compose :: (b -> c) -> (a -> b) -> a -> c
const compose = curry((f, g, x) => f(g(x)));
// countWhere :: (a -> Bool) -> [a] -> Number
const countWhere = compose(compose(length), filter);
According to the following question countWhere is defined as (length .) . filter:
What does (f .) . g mean in Haskell?
Hence I should be able to use countWhere as follows:
const odd = n => n % 2 === 1;
countWhere(odd, [1,2,3,4,5]);
However, instead of returning 3 (the length of the array [1,3,5]), it returns a function. What am I doing wrong?
#Aadit,
I'm posting this because you shared a comment on my answer to To “combine” functions in javascript in a functional way? I didn't specifically cover currying in that post because it's a very contentious topic and not really a can of worms I wanted to open there.
I'd be wary using the phrasing "how to correctly curry" when you seem to be adding your own sugar and conveniences into your implementation.
Anyway, all of that aside, I truly don't intend for this to be an argumentative/combative post. I'd like to be able to have an open, friendly discussion about currying in JavaScript while emphasizing some of the differences between our approaches.
Without further ado...
To clarify:
Given f is a function and f.length is n. Let curry(f) be g. We call g with m arguments. What should happen? You say:
If m === 0 then just return g.
If m < n then partially apply f to the m new arguments, and return a new curried function which accepts the remaining n - m arguments.
If m === n then apply f to the m arguments. If the result is a function then curry the result. Finally, return the result.
If m > n then apply f to the first n arguments. If the result is a function then curry the result. Finally, apply the result to the remaining m - n arguments and return the new result.
Let's see a code example of what #Aadit M Shah's code actually does
var add = curry(function(x, y) {
return function(a, b) {
return x + y + a + b;
}
});
var z = add(1, 2, 3);
console.log(z(4)); // 10
There are two things happening here:
You're attempting to support calling curried functions with variadic arguments.
You're automatically currying returned functions
I don't believe there's a lot of room for debate here, but people seem to miss what currying actually is
via: Wikipedia
In mathematics and computer science, currying is the technique of translating the evaluation of a function that takes multiple arguments (or a tuple of arguments) into evaluating a sequence of functions, each with a single argument...
I'm bolding that last bit, because it's so important; each function in the sequence only takes a single argument; not variadic (0, 1, or more) arguments like you suggest.
You mention haskell in your post, too, so I assume you know that Haskell has no such thing as functions that take more than one argument. (Note: a function that takes a tuple is still just a function that takes one argument, a single tuple). The reasons for this are profound and afford you a flexibility in expressiveness not afforded to you by functions with variadic arguments.
So let's re-ask that original question: What should happen?
Well, it's simple when each function only accepts 1 argument. At any time, if more than 1 argument is given, they're just dropped.
function id(x) {
return x;
}
What happens when we call id(1,2,3,4)? Of course we only get the 1 back and 2,3,4 are completely disregarded. This is:
how JavaScript works
how Wikipedia says currying should work
how we should implement our own curry solution
Before we go further, I'm going to use ES6-style arrow functions but I will also include the ES5 equivalent at the bottom of this post. (Probably later tonight.)
another currying technique
In this approach, we write a curry function that continuously returns single-parameter functions until all arguments have been specified
As a result of this implementation we have 6 multi-purpose functions.
// no nonsense curry
const curry = f => {
const aux = (n, xs) =>
n === 0 ? f (...xs) : x => aux (n - 1, [...xs, x])
return aux (f.length, [])
}
// demo
let sum3 = curry(function(x,y,z) {
return x + y + z;
});
console.log (sum3 (3) (5) (-1)); // 7
OK, so we've seen a curry technique that is implemented using a simple auxiliary loop. It has no dependencies and a declarative definition that is under 5 lines of code. It allows functions to be partially applied, 1 argument at a time, just as a curried function is supposed to work.
No magic, no unforeseen auto-currying, no other unforeseen consequences.
But what really is the point of currying anyway?
Well, as it turns out, I don't really curry functions that I write. As you can see below, I generally define all of my reusable functions in curried form. So really, you only need curry when you want to interface with some functions that you don't have control over, perhaps coming from a lib or something; some of which might have variadic interfaces!
I present curryN
// the more versatile, curryN
const curryN = n => f => {
const aux = (n, xs) =>
n === 0 ? f (...xs) : x => aux (n - 1, [...xs, x])
return aux (n, [])
};
// curry derived from curryN
const curry = f => curryN (f.length) (f);
// some caveman function
let sumN = function() {
return [].slice.call(arguments).reduce(function(a, b) {
return a + b;
});
};
// curry a fixed number of arguments
let g = curryN (5) (sumN);
console.log (g (1) (2) (3) (4) (5)); // 15
To curry or not to curry? That is the question
We'll write some examples where our functions are all in curried form. Functions will be kept extremely simple. Each with 1 parameter, and each with a single return expression.
// composing two functions
const comp = f => g => x => f (g (x))
const mod = y => x => x % y
const eq = y => x => x === y
const odd = comp (eq (1)) (mod (2))
console.log (odd(1)) // true
console.log (odd(2)) // false
Your countWhere function
// comp :: (b -> c) -> (a -> b) -> (a -> c)
const comp = f => g => x =>
f(g(x))
// mod :: Int -> Int -> Int
const mod = x => y =>
y % x
// type Comparable = Number | String
// eq :: Comparable -> Comparable -> Boolean
const eq = x => y =>
y === x
// odd :: Int -> Boolean
const odd =
comp (eq(1)) (mod(2))
// reduce :: (b -> a -> b) -> b -> ([a]) -> b
const reduce = f => y => ([x,...xs]) =>
x === undefined ? y : reduce (f) (f(y)(x)) (xs)
// filter :: (a -> Boolean) -> [a] -> [a]
const filter = f =>
reduce (acc => x => f (x) ? [...acc,x] : acc) ([])
// length :: [a] -> Int
const length = x =>
x.length
// countWhere :: (a -> Boolean) -> [a] -> Int
const countWhere = f =>
comp (length) (filter(f));
console.log (countWhere (odd) ([1,2,3,4,5]))
// 3
Remarks
So to curry or not to curry?
// to curry
const add3 = curry((a, b, c) =>
a + b + c
)
// not to curry
const add3 = a => b => c =>
a + b + c
With ES6 arrow functions being the go-to choice for today's JavaScripter, I think the choice to manually curry your functions is a no-brainer. It's actually shorter and has less overhead to just write it out in curried form.
That said, you're still going to be interfacing with libs that do not offer curried forms of the functions they expose. For this situation, I'd recommend
curry and curryN (defined above)
partial (as defined here)
#Iven,
Your curryN implementation is very nice. This section exists solely for you.
const U = f=> f (f)
const Y = U (h=> f=> f(x=> h (h) (f) (x)))
const curryN = Y (h=> xs=> n=> f=>
n === 0 ? f(...xs) : x=> h ([...xs, x]) (n-1) (f)
) ([])
const curry = f=> curryN (f.length) (f)
const add3 = curry ((x,y,z)=> x + y + z)
console .log (add3 (3) (6) (9))
The problem with your curry function (and for most curry functions that people write in JavaScript) is that it doesn't handle extra arguments correctly.
What curry does
Suppose f is a function and f.length is n. Let curry(f) be g. We call g with m arguments. What should happen?
If m === 0 then just return g.
If m < n then partially apply f to the m new arguments, and return a new curried function which accepts the remaining n - m arguments.
Otherwise apply f to the m arguments and return the result.
This is what most curry functions do, and this is wrong. The first two cases are right, but the third case is wrong. Instead, it should be:
If m === 0 then just return g.
If m < n then partially apply f to the m new arguments, and return a new curried function which accepts the remaining n - m arguments.
If m === n then apply f to the m arguments. If the result is a function then curry the result. Finally, return the result.
If m > n then apply f to the first n arguments. If the result is a function then curry the result. Finally, apply the result to the remaining m - n arguments and return the new result.
The problem with most curry functions
Consider the following code:
const countWhere = compose(compose(length), filter);
countWhere(odd, [1,2,3,4,5]);
If we use the incorrect curry functions, then this is equivalent to:
compose(compose(length), filter, odd, [1,2,3,4,5]);
However, compose only accepts three arguments. The last argument is dropped:
const compose = curry((f, g, x) =>f(g(x)));
Hence, the above expression evaluates to:
compose(length)(filter(odd));
This further evaluates to:
compose(length, filter(odd));
The compose function expects one more argument which is why it returns a function instead of returning 3. To get the correct output you need to write:
countWhere(odd)([1,2,3,4,5]);
This is the reason why most curry functions are wrong.
The solution using the correct curry function
Consider the following code again:
const countWhere = compose(compose(length), filter);
countWhere(odd, [1,2,3,4,5]);
If we use the correct curry function, then this is equivalent to:
compose(compose(length), filter, odd)([1,2,3,4,5]);
Which evaluates to:
compose(length)(filter(odd))([1,2,3,4,5]);
Which further evaluates to (skipping an intermediate step):
compose(length, filter(odd), [1,2,3,4,5]);
Which results in:
length(filter(odd, [1,2,3,4,5]));
Producing the correct result 3.
The implementation of the correct curry function
Implementing the correct curry function in ES6 is straightforward:
const curry = (f, ...a) => {
const n = f.length, m = a.length;
if (n === 0) return m > n ? f(...a) : f;
if (m === n) return autocurry(f(...a));
if (m < n) return (...b) => curry(f, ...a, ...b);
return curry(f(...a.slice(0, n)), ...a.slice(n));
};
const autocurry = (x) => typeof x === "function" ? curry(x) : x;
Note that if the length of the input function is 0 then it's assumed to be curried.
Implications of using the correct curry function
Using the correct curry function allows you to directly translate Haskell code into JavaScript. For example:
const id = curry(a => a);
const flip = curry((f, x, y) => f(y, x));
The id function is useful because it allows you to partially apply a non-curried function easily:
const add = (a, b) => a + b;
const add2 = id(add, 2);
The flip function is useful because it allows you to easily create right sections in JavaScript:
const sub = (a, b) => a - b;
const sub2 = flip(sub, 2); // equivalent to (x - 2)
It also means that you don't need hacks like this extended compose function:
What's a Good Name for this extended `compose` function?
You can simply write:
const project = compose(map, pick);
As mentioned in the question, if you want to compose length and filter then you use the (f .) . g pattern:
What does (f .) . g mean in Haskell?
Another solution is to create higher order compose functions:
const compose2 = compose(compose, compose);
const countWhere = compose2(length, fitler);
This is all possible because of the correct implementation of the curry function.
Extra food for thought
I usually use the following chain function when I want to compose a chain of functions:
const chain = compose((a, x) => {
var length = a.length;
while (length > 0) x = a[--length](x);
return x;
});
This allows you to write code like:
const inc = add(1);
const foo = chain([map(inc), filter(odd), take(5)]);
foo([1,2,3,4,5,6,7,8,9,10]); // [2,4,6]
Which is equivalent to the following Haskell code:
let foo = map (+1) . filter odd . take 5
foo [1,2,3,4,5,6,7,8,9,10]
It also allows you to write code like:
chain([map(inc), filter(odd), take(5)], [1,2,3,4,5,6,7,8,9,10]); // [2,4,6]
Which is equivalent to the following Haskell code:
map (+1) . filter odd . take 5 $ [1,2,3,4,5,6,7,8,9,10]
Hope that helps.
Apart from its mathematical definition
currying is the transformation of a function with n parameters into a sequence of n functions, which each accept a single parameter. The arity is thus transformed from n-ary to n * 1-ary
what impact has currying on programming? Abstraction over arity!
const comp = f => g => x => f(g(x));
const inc = x => x + 1;
const mul = y => x => x * y;
const sqr = x => mul(x)(x);
comp(sqr)(inc)(1); // 4
comp(mul)(inc)(1)(2); // 4
comp expects two functions f and g and a single arbitrary argument x. Consequently g must be an unary function (a function with exactly one formal parameter) and f too, since it is fed with the return value of g. It won't surprise anyone that comp(sqr)(inc)(1) works. sqr and inc are both unary.
But mul is obviously a binary function. How on earth is that going to work? Because currying abstracted the arity of mul. You can now probably imagine what a powerful feature currying is.
In ES2015 we can pre-curry our functions with arrow functions succinctly:
const map = (f, acc = []) => xs => xs.length > 0
? map(f, [...acc, f(xs[0])])(xs.slice(1))
: acc;
map(x => x + 1)([1,2,3]); // [2,3,4]
Nevertheless, we need a programmatic curry function for all functions out of our control. Since we learned that currying primarily means abstraction over arity, our implementation must not depend on Function.length:
const curryN = (n, acc = []) => f => x => n > 1
? curryN(n - 1, [...acc, x])(f)
: f(...acc, x);
const map = (f, xs) => xs.map(x => f(x));
curryN(2)(map)(x => x + 1)([1,2,3]); // [2,3,4]
Passing the arity explicitly to curryN has the nice side effect that we can curry variadic functions as well:
const sum = (...args) => args.reduce((acc, x) => acc + x, 0);
curryN(3)(sum)(1)(2)(3); // 6
One problem remains: Our curry solution can't deal with methods. OK, we can easily redefine methods that we need:
const concat = ys => xs => xs.concat(ys);
const append = x => concat([x]);
concat([4])([1,2,3]); // [1,2,3,4]
append([4])([1,2,3]); // [1,2,3,[4]]
An alternative is to adapt curryN in a manner that it can handle both multi-argument functions and methods:
const curryN = (n, acc = []) => f => x => n > 1
? curryN(n - 1, [...acc, x])(f)
: typeof f === "function"
? f(...acc, x)
: x[f](...acc);
curryN(2)("concat")(4)([1,2,3]); // [1,2,3,4]
I don't know if this is the correct way to curry functions (and methods) in Javascript though. It is rather one possible way.
EDIT:
naomik pointed out that by using a default value the internal API of the curry function is partially exposed. The achieved simplification of the curry function comes thus at the expense of its stability. To avoid API leaking we need a wrapper function. We can utilize the U combinator (similar to naomik's solution with Y):
const U = f => f(f);
const curryN = U(h => acc => n => f => x => n > 1
? h(h)([...acc, x])(n-1)(f)
: f(...acc, x))([]);
Drawback: The implementation is harder to read and has a performance penalty.
//---Currying refers to copying a function but with preset parameters
function multiply(a,b){return a*b};
var productOfSixNFiveSix = multiply.bind(this,6,5);
console.log(productOfSixNFive());
//The same can be done using apply() and call()
var productOfSixNFiveSix = multiply.call(this,6,5);
console.log(productOfSixNFive);
var productOfSixNFiveSix = multiply.apply(this,[6,5]);
console.log(productOfSixNFive);