What is 'Currying'?

前端 未结 18 1265
遥遥无期
遥遥无期 2020-11-21 05:26

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

18条回答
  •  日久生厌
    2020-11-21 06:07

    Currying is translating a function from callable as f(a, b, c) into callable as f(a)(b)(c).

    Otherwise currying is when you break down a function that takes multiple arguments into a series of functions that take part of the arguments.

    Literally, currying is a transformation of functions: from one way of calling into another. In JavaScript, we usually make a wrapper to keep the original function.

    Currying doesn’t call a function. It just transforms it.

    Let’s make curry function that performs currying for two-argument functions. In other words, curry(f) for two-argument f(a, b) translates it into f(a)(b)

    function curry(f) { // curry(f) does the currying transform
      return function(a) {
        return function(b) {
          return f(a, b);
        };
      };
    }
    
    // usage
    function sum(a, b) {
      return a + b;
    }
    
    let carriedSum = curry(sum);
    
    alert( carriedSum(1)(2) ); // 3
    

    As you can see, the implementation is a series of wrappers.

    • The result of curry(func) is a wrapper function(a).
    • When it is called like sum(1), the argument is saved in the Lexical Environment, and a new wrapper is returned function(b).
    • Then sum(1)(2) finally calls function(b) providing 2, and it passes the call to the original multi-argument sum.

提交回复
热议问题