什么是'Currying'? [英] What is 'Currying'?
问题描述
我在几篇文章和博客中看到了curried函数的引用,但是我找不到一个好的解释(或者至少有一个是合理的!)
$ b
function add(a, b){
return a + b;
}
add(3,4); //返回7
这是一个函数,它接受两个参数a和b,并返回它们的和。我们现在将会使用这个函数:
$ b
function add(a){
return function (b){
返回a + b;
$ b $ p
$ b 这是一个函数,它带有一个参数a,并返回一个函数,它接受另一个参数b,并且该函数返回它们的总和。
add (3)(4);
var add3 = add(3);
add3(4);
第一条语句返回7,就像add(3,4)语句一样。第二个语句定义了一个名为add3的新函数,它将在其参数中加3。这是有些人可能会称之为封闭的。第三条语句使用add3操作将3添加到4,结果再次生成7。
I've seen references to curried functions in several articles and blogs but I can't find a good explanation (or at least one that makes sense!)
解决方案 Currying is when you break down a function that takes multiple arguments into a series of functions that take part of the arguments. Here's an example in JavaScript:
function add (a, b) {
return a + b;
}
add(3, 4); // returns 7
This is a function that takes two arguments, a and b, and returns their sum. We will now curry this function:
function add (a) {
return function (b) {
return a + b;
}
}
This is a function that takes one argument, a, and returns a function that takes another argument, b, and that function returns their sum.
add(3)(4);
var add3 = add(3);
add3(4);
The first statement returns 7, like the add(3, 4) statement. The second statement defines a new function called add3 that will add 3 to its argument. This is what some people may call a closure. The third statement uses the add3 operation to add 3 to 4, again producing 7 as a result.
这篇关于什么是'Currying'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!