从Haskell到Python:怎么做currying?

bur*_*y_5 3 python haskell function currying

我最近开始使用Python进行编码,我想知道是否可以返回专门用于其他功能的函数.

例如,在Haskell中,您可以创建一个向任何给定数字添加5的函数,如下所示:

sumFive = (+5)
Run Code Online (Sandbox Code Playgroud)

在Python中以某种方式可能吗?

oba*_*adz 5

我认为其他答案误解了这个问题.我相信OP正在询问部分应用函数,在他的例子中函数是(+).

如果目标不是部分应用,那么解决方案就像:

def sumFive(x): return x + 5
Run Code Online (Sandbox Code Playgroud)

对于Python中的部分应用程序,我们可以使用此函数:https://docs.python.org/2/library/functools.html#functools.partial

def partial(func, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = keywords.copy()
        newkeywords.update(fkeywords)
        return func(*(args + fargs), **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
Run Code Online (Sandbox Code Playgroud)

然后,我们必须将+运算符转换为函数(我不相信有像Haskell那样的轻量级语法):

def plus(x, y): return x + y
Run Code Online (Sandbox Code Playgroud)

最后:

sumFive = partial(plus, 5)
Run Code Online (Sandbox Code Playgroud)

不像Haskell那么好,但它有效:

>>> sumFive(7)
12
Run Code Online (Sandbox Code Playgroud)

  • 那个'plus`函数已经在标准库中了:https://docs.python.org/3.5/library/operator.html#operator.add (2认同)