JS Curry函数与递归 [英] JS Curry function with Recursion
问题描述
函数乘法(... args){
return args.reduce((accum,val)=> accum * val,1)
}
但是我试图实现别的东西......
这个函数应该将它的curry函数括号以及。
例如
/ *
返回三个数字的乘积。
该函数可以以下列任何形式调用:
multiply(2,3)(4)=> 24
乘(2)(3,4)=> 24
乘(2)(3)(4)=> 24
乘(2,3,4)=> 24
* /
请帮助。
经过大量代码并阅读一些堆栈答案后。
最后我想出了。但它仍然不满足 multiply(2)(3,4)=> 24
但对于其余案例正常工作
乘(2,3,4)
乘(2,3)(4)
乘(2)(3)(4)
var multiply = function(... args){
if(args.length === 3){
return args [0] * args [1] * args [2];
} else {
return function(){
args.push([]。slice.call(arguments).pop());
返回multiply.apply(this,args);
};
$ p $ multiply(2) (3,4)=> 24失败
解决方案这是一个通过反复调用 bind
直到有足够的参数传递完毕。
function a * b * c); console.log(multiply(2,3)(4)); console.log(multiply(2)( ); console.log(multiply(2)(3)(4)); console.log(multiply(2,3,4));
Kindly read before you mark it as duplicate.
Im not asking for single curry call.
This functions multiplies, multiplication(4,4,4) //64
function multiplication(...args) {
return args.reduce((accum, val) => accum * val, 1)
}
But Im trying to achieve something else...
This same function should multiply its curry function parenthesis as well.
e.g.
/*
which return the multiplication of three numbers.
The function can be called in any of the following forms:
multiply(2, 3)(4) => 24
multiply(2)(3, 4) => 24
multiply(2)(3)(4) => 24
multiply(2, 3, 4) => 24
*/
Kindly help.
After fiddling through a lot of code and reading some stack answers.
Finally I came up with. But it still doesnt satisfy this multiply(2)(3, 4) => 24
But works fine for rest of the cases
multiply(2,3,4)
multiply(2,3)(4)
multiply(2)(3)(4)
var multiply = function(...args) {
if (args.length === 3) {
return args[0] * args[1] * args[2];
} else {
return function() {
args.push([].slice.call(arguments).pop());
return multiply.apply(this, args);
};
}
}
while multiply(2)(3, 4) => 24 fail
解决方案 Here's a generalized solution that works by repeatedly calling bind
until enough parameters have been passed.
function curry(func, arity = func.length) {
return function (...args) {
if (args.length >= arity) {
return func(...args);
} else {
return curry(func.bind(this, ...args), arity - args.length);
}
};
}
const multiply = curry((a, b, c) => a * b * c);
console.log(multiply(2, 3)(4));
console.log(multiply(2)(3, 4));
console.log(multiply(2)(3)(4));
console.log(multiply(2, 3, 4));
这篇关于JS Curry函数与递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!