我在一些文章和博客中看到了curry函数的引用,但我找不到一个好的解释(或者至少一个有意义的解释!)


当前回答

下面是JavaScript中的一个curry示例,这里的multiply返回用于将x乘以2的函数。

const multiply = (presetConstant) => {
  return (x) => {
    return presetConstant * x;
  };
};

const multiplyByTwo = multiply(2);

// now multiplyByTwo is like below function & due to closure property in JavaScript it will always be able to access 'presetConstant' value
// const multiplyByTwo = (x) => {
//   return presetConstant * x;
// };

console.log(`multiplyByTwo(8) : ${multiplyByTwo(8)}`);

输出

multiplyByTwo(8): 16

其他回答

curry是指将一个接受多个参数的函数分解为一系列函数,每个函数只接受一个参数。下面是JavaScript的一个例子:

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

add(3, 4); // returns 7

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

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

这是一个接受一个参数a的函数,并返回一个接受另一个参数b的函数,该函数返回它们的和。

add(3)(4); // returns 7

var add3 = add(3); // returns a function

add3(4); // returns 7

第一个语句返回7,就像add(3,4)语句一样。 第二条语句定义了一个名为add3的新函数 给它的参数加上3。(这就是有些人所说的终结。) 第三条语句再次使用add3操作将3添加到4 结果是7。

在这里,您可以找到c#中curry实现的简单解释。在评论中,我试图展示咖喱是如何有用的:

public static class FuncExtensions {
    public static Func<T1, Func<T2, TResult>> Curry<T1, T2, TResult>(this Func<T1, T2, TResult> func)
    {
        return x1 => x2 => func(x1, x2);
    }
}

//Usage
var add = new Func<int, int, int>((x, y) => x + y).Curry();
var func = add(1);

//Obtaining the next parameter here, calling later the func with next parameter.
//Or you can prepare some base calculations at the previous step and then
//use the result of those calculations when calling the func multiple times 
//with different input parameters.

int result = func(1);

Curry可以简化代码。这是使用它的主要原因之一。curry是将一个接受n个参数的函数转换为n个只接受一个参数的函数的过程。

其原理是传递传递函数的参数,使用closure(闭包)属性,将它们存储在另一个函数中并将其作为返回值,这些函数形成一个链,最后的参数被传递进来完成操作。

这样做的好处是可以通过一次处理一个参数来简化参数的处理,也可以提高程序的灵活性和可读性。这也使程序更易于管理。此外,将代码分割成更小的片段将使其易于重用。

例如:

function curryMinus(x) 
{
  return function(y) 
  {
    return x - y;
  }
}

var minus5 = curryMinus(1);
minus5(3);
minus5(5);

我还可以做…

var minus7 = curryMinus(7);
minus7(3);
minus7(5);

这对于使复杂的代码变得整洁和处理非同步方法等非常有用。

其他答案已经说明了curry是什么:向curry函数传递的参数比它预期的要少,这不是错误,而是返回一个函数,该函数预期其余的参数,并返回相同的结果,就好像您一次性将它们全部传入一样。

我会试着解释为什么它有用。这是一种你从未意识到你需要的工具,直到你真正使用它。curry首先是一种让你的程序更具表现力的方法——你可以用更少的代码把操作组合在一起。

For example, if you have a curried function add, you can write the equivalent of JS x => k + x (or Python lambda x: k + x or Ruby { |x| k + x } or Lisp (lambda (x) (+ k x)) or …) as just add(k). In Haskelll you can even use the operator: (k +) or (+ k) (The two forms let you curry either way for non-commutative operators: (/ 9) is a function that divides a number by 9, which is probably the more common use case, but you also have (9 /) for a function that divides 9 by its argument.) Besides being shorter, the curried version contains no made-up parameter name like the x found in all the other versions. It’s not needed. You’re defining a function that adds some constant k to a number, and you don’t need to give that number a name just to talk about the function. Or even to define it. This is an example of what’s called “point-free style”. You can combine operations together given nothing but the operations themselves. You don’t have to declare anonymous functions that do nothing but apply some operation to their argument, because *that’s what the operations already are.

当以咖喱友好的方式定义高阶函数时,这变得非常方便。例如,curried map(fn, list)让您定义一个只使用map(fn)的映射器,可以稍后将其应用于任何列表。但是将定义为map(list, fn)的映射curry化只能让您定义一个将其他函数应用到常量列表的函数,这在一般情况下可能不太有用。

Currying reduces the need for things like pipes and threading. In Clojure, you might define a temperature conversion function using the threading macro ->: (defn f2c (deg) (-> deg (- 32) (* 5) (/ 9)). That’s cool, it reads nicely left to right (“subtract 32, multiply by 5 and divide by 9.”) and you only have to mention the parameter twice instead of once for every suboperation… but it only works because -> is a macro that transforms the whole form syntactically before anything is evaluated. It turns into a regular nested expression behind the scenes: (/ (* (- deg 32) 5) 9). If the math ops were curried, you wouldn’t need a macro to combine them so nicely, as in Haskell let f2c = (subtract 32) & (* 5) & (/ 9). (Although it would admittedly be more idiomatic to use function composition, which reads right to left: (/ 9) . (* 5) . (subtract 32).)

同样,很难找到好的演示例子;在复杂的情况下,咖喱是最有用的,因为它确实有助于解决方案的可读性,但这些需要太多的解释才能让您理解问题,以至于关于咖喱的整个课程可能会淹没在噪音中。

curry是指将一个N次的函数转换为N次1次的函数。函数的元数是它所需要的参数的个数。

下面是正式的定义:

 curry(f) :: (a,b,c) -> f(a) -> f(b)-> f(c)

下面是一个真实的例子:

你去自动取款机取钱。你刷你的卡,输入密码,做出选择,然后按enter键提交“金额”和请求。

这是取款的正常功能。

const withdraw=(cardInfo,pinNumber,request){
    // process it
       return request.amount
}

在这个实现函数中,我们希望一次性输入所有参数。我们将刷卡,输入密码并发出请求,然后函数将运行。如果这些步骤中有任何问题,在输入所有参数后就会发现。使用curry函数,我们可以创建更高的、纯粹的和简单的函数。纯函数将帮助我们轻松地调试代码。

这是带有咖喱功能的Atm机。

const withdraw=(cardInfo)=>(pinNumber)=>(request)=>request.amount

ATM, takes the card as input and returns a function that expects pinNumber and this function returns a function that accepts the request object and after the successful process, you get the amount that you requested. Each step, if you had an error, you will easily predict what went wrong. Let's say you enter the card and got error, you know that it is either related to the card or machine but not the pin number. Or if you entered the pin and if it does not get accepted you know that you entered the pin number wrong. You will easily debug the error.

此外,这里的每个函数都是可重用的,因此您可以在项目的不同部分使用相同的函数。