What is 'Currying'?

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

    Here's a toy example in Python:

    >>> from functools import partial as curry
    
    >>> # Original function taking three parameters:
    >>> def display_quote(who, subject, quote):
            print who, 'said regarding', subject + ':'
            print '"' + quote + '"'
    
    
    >>> display_quote("hoohoo", "functional languages",
               "I like Erlang, not sure yet about Haskell.")
    hoohoo said regarding functional languages:
    "I like Erlang, not sure yet about Haskell."
    
    >>> # Let's curry the function to get another that always quotes Alex...
    >>> am_quote = curry(display_quote, "Alex Martelli")
    
    >>> am_quote("currying", "As usual, wikipedia has a nice summary...")
    Alex Martelli said regarding currying:
    "As usual, wikipedia has a nice summary..."
    

    (Just using concatenation via + to avoid distraction for non-Python programmers.)

    Editing to add:

    See http://docs.python.org/library/functools.html?highlight=partial#functools.partial, which also shows the partial object vs. function distinction in the way Python implements this.

    0 讨论(0)
  • 2020-11-21 06:05

    I found this article, and the article it references, useful, to better understand currying: http://blogs.msdn.com/wesdyer/archive/2007/01/29/currying-and-partial-function-application.aspx

    As the others mentioned, it is just a way to have a one parameter function.

    This is useful in that you don't have to assume how many parameters will be passed in, so you don't need a 2 parameter, 3 parameter and 4 parameter functions.

    0 讨论(0)
  • 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.
    0 讨论(0)
  • An example of currying would be when having functions you only know one of the parameters at the moment:

    For example:

    func aFunction(str: String) {
        let callback = callback(str) // signature now is `NSData -> ()`
        performAsyncRequest(callback)
    }
    
    func callback(str: String, data: NSData) {
        // Callback code
    }
    
    func performAsyncRequest(callback: NSData -> ()) {
        // Async code that will call callback with NSData as parameter
    }
    

    Here, since you don't know the second parameter for callback when sending it to performAsyncRequest(_:) you would have to create another lambda / closure to send that one to the function.

    0 讨论(0)
  • 2020-11-21 06:10

    A curried function is a function of several arguments rewritten such that it accepts the first argument and returns a function that accepts the second argument and so on. This allows functions of several arguments to have some of their initial arguments partially applied.

    0 讨论(0)
  • 2020-11-21 06:11

    Currying is one of the higher-order functions of Java Script.

    Currying is a function of many arguments which is rewritten such that it takes the first argument and return a function which in turns uses the remaining arguments and returns the value.

    Confused?

    Let see an example,

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

    This is similar to the following currying function,

    function add(a)
        {
            return function(b){
                return a+b;
            }
        }
    var curryAdd = add(5);
    curryAdd(6);
    

    So what does this code means?

    Now read the definition again,

    Currying is a function of many arguments which is rewritten such that it takes first argument and return a function which in turns uses the remaining arguments and returns the value.

    Still, Confused? Let me explain in deep!

    When you call this function,

    var curryAdd = add(5);
    

    It will return you a function like this,

    curryAdd=function(y){return 5+y;}
    

    So, this is called higher-order functions. Meaning, Invoking one function in turns returns another function is an exact definition for higher-order function. This is the greatest advantage for the legend, Java Script. So come back to the currying,

    This line will pass the second argument to the curryAdd function.

    curryAdd(6);
    

    which in turns results,

    curryAdd=function(6){return 5+6;}
    // Which results in 11
    

    Hope you understand the usage of currying here. So, Coming to the advantages,

    Why Currying?

    It makes use of code reusability. Less code, Less Error. You may ask how it is less code?

    I can prove it with ECMA script 6 new feature arrow functions.

    Yes! ECMA 6, provide us with the wonderful feature called arrow functions,

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

    With the help of the arrow function, we can write the above function as follows,

    x=>y=>x+y
    

    Cool right?

    So, Less Code and Fewer bugs!!

    With the help of these higher-order function one can easily develop a bug-free code.

    I challenge you!

    Hope, you understood what is currying. Please feel free to comment over here if you need any clarifications.

    Thanks, Have a nice day!

    0 讨论(0)
提交回复
热议问题