什么是“柯里化"?

我在几篇文章和博客中看到了对柯里化函数的引用,但我找不到一个好的解释(或者至少是一个有意义的解释!)

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!)

推荐答案

柯里化是将一个接受多个参数的函数分解为一系列函数,每个函数只接受一个参数.下面是一个 JavaScript 示例:

Currying is when you break down a function that takes multiple arguments into a series of functions that each take only one argument. Here's an example in JavaScript:

function add (a, b) {
  return a + b;
}

add(3, 4); // returns 7

这是一个函数,它接受两个参数,a 和 b,并返回它们的和.我们现在将 curry 这个函数:

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;
  }
}

这是一个函数,它接受一个参数 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);

第一个语句返回 7,就像 add(3, 4) 语句一样.第二条语句定义了一个名为 add3 的新函数,它将向其参数添加 3.(有些人可能称之为闭包.)第三条语句使用 add3 操作将 3 与 4 相加,结果再次生成 7.

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 may call a closure.) The third statement uses the add3 operation to add 3 to 4, again producing 7 as a result.

相关文章