繁体   English   中英

咖喱 javascript sum 函数。

[英]Curried javascript sum function.

我遇到了这个有趣的问题。 编写一个 javascript 函数,通过对同一函数的多次调用,返回传递给它的所有参数的总和。

以下是调用函数的方式 -

 sum(1, 2, 3, 4); sum(1, 2)(3, 4); sum(1, 2)(3)(4); sum(1, 2, 3)(4); sum(1)(2, 3, 4);

上面的所有调用都应该工作并返回 10。

这是我到目前为止所写的内容,但它仅适用于前两个函数调用sum(1, 2, 3, 4)sum(1, 2)(3, 4)并为其余部分拉屎。

 const arr = []; function sum(...args) { if (args.length === 4) { return args.reduce((acc, curr) => { return (acc = acc + curr); }, 0); } else { arr.push(...args); return function(...args) { arr.push(...args); return sum(...arr); }; } }

有人请帮助我,这让我发疯。

谢谢!

你很接近。 这是使用.bind方法返回捕获第一个参数的函数的绝佳机会,如果您还没有获得至少四个参数。

所以像:

 function sum(...args) { if (args.length >= 4) { return args.reduce((acc, curr) => { return (acc = acc + curr); }, 0); } else { // Bind the arguments you have to this function, and return it: return sum.bind(null, ...args) } } console.log(sum(1, 2, 3, 4)); console.log(sum(1, 2)(3, 4)); console.log(sum(1, 2)(3)(4)); console.log(sum(1, 2, 3)(4)); console.log(sum(1)(2, 3, 4));

最后,我会更改条件以检查>= 4以便传递超过这个值不会导致您永远咖喱的情况。

柯里化具有特定且定义的行为,由于未定义的元数,它不能与可变参数函数很好地混合。 但是,在您的特定问题中,您指定了一个 arity(例如,4),因此可以知道何时返回结果

 const curryN = (n, f, ...xs) => (...ys) => ys.length >= n ? f (...xs, ...ys) : curryN (n - ys.length, f, ...xs, ...ys) const add = (...numbers) => numbers.reduce ((a, b) => a + b, 0) const curryAdd = curryN (4, add) console.log ( curryAdd (1) (2) (3) (4) // 10 , curryAdd (1, 2) (3, 4) // 10 , curryAdd (1, 2, 3) (4) // 10 , curryAdd (1) (2, 3, 4) // 10 , curryAdd (1, 2, 3, 4) // 10 )

但是,这是设计程序的一种脆弱方式,它甚至不是真正的柯里化,每个应用程序只接受 1 个参数。 部分应用程序更好,因为它生成的程序具有更可靠的行为

 const partial = (f, ...xs) => (...ys) => f (...xs, ...ys) const add = (...numbers) => numbers.reduce ((a, b) => a + b, 0) console.log ( partial (add, 1) (2, 3, 4) // 10 , partial (add, 1, 2) (3, 4) // 10 , partial (add, 1, 2, 3) (4) // 10 )

请阅读此相关答案以获取更多见解。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM