What is 'Currying'?

前端 未结 18 1288
遥遥无期
遥遥无期 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:14

    It can be a way to use functions to make other functions.

    In javascript:

    let add = function(x){
      return function(y){ 
       return x + y
      };
    };
    

    Would allow us to call it like so:

    let addTen = add(10);
    

    When this runs the 10 is passed in as x;

    let add = function(10){
      return function(y){
        return 10 + y 
      };
    };
    

    which means we are returned this function:

    function(y) { return 10 + y };
    

    So when you call

     addTen();
    

    you are really calling:

     function(y) { return 10 + y };
    

    So if you do this:

     addTen(4)
    

    it's the same as:

    function(4) { return 10 + 4} // 14
    

    So our addTen() always adds ten to whatever we pass in. We can make similar functions in the same way:

    let addTwo = add(2)       // addTwo(); will add two to whatever you pass in
    let addSeventy = add(70)  // ... and so on...
    

    Now the obvious follow up question is why on earth would you ever want to do that? It turns what was an eager operation x + y into one that can be stepped through lazily, meaning we can do at least two things 1. cache expensive operations 2. achieve abstractions in the functional paradigm.

    Imagine our curried function looked like this:

    let doTheHardStuff = function(x) {
      let z = doSomethingComputationallyExpensive(x)
      return function (y){
        z + y
      }
    }
    

    We could call this function once, then pass around the result to be used in lots of places, meaning we only do the computationally expensive stuff once:

    let finishTheJob = doTheHardStuff(10)
    finishTheJob(20)
    finishTheJob(30)
    

    We can get abstractions in a similar way.

提交回复
热议问题