What is 'Currying'?

前端 未结 18 1261
遥遥无期
遥遥无期 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.

提交回复
热议问题