什么是“咖喱"? [英] What is 'Currying'?

查看:33
本文介绍了什么是“咖喱"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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,并返回它们的总和.我们现在将柯里化这个函数:

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.

这篇关于什么是“咖喱"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆