且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么时候应该在 Python 中使用函数柯里化?

更新时间:2023-02-16 22:53:55

函数柯里化的目的是方便地从更通用的函数中获取专门的函数.你可以通过在不同的时间并在之后保持固定.

The purpose of function currying is to easily get specialized functions from more general functions. You achieve this by pre-setting some parameters at a different time and keeping them fixed afterwards.

与命名无关.在 Python 中,您可以随时轻松地重命名变量/函数.

It has nothing to do with the naming. In Python you can rename a variable/function easily at all times.

示例:

def simple_function(a):
    def line(b=0):
        def compute(x):
            return [a+b * xi for xi in x]
        return compute
    return line

x = range(-4, 4, 1)
print('x {}'.format(list(x)))
print('constant {}'.format(simple_function(3)()(x)))
print('line {}'.format(simple_function(3)(-2)(x)))

给予

x [-4, -3, -2, -1, 0, 1, 2, 3]
constant [3, 3, 3, 3, 3, 3, 3, 3]
line [11, 9, 7, 5, 3, 1, -1, -3]

现在这还不是那么令人兴奋.它仅将 f(a,b,c) 类型的函数调用替换为 f(a)(b)(c) 类型的调用,这甚至可能被视为Python 中不太优雅的风格.

Now this was not yet that exciting. It only replaced functions calls of type f(a,b,c) with calls of type f(a)(b)(c) which might even be seen as the less elegant style in Python.

但它允许你做:

line_through_zero = simple_function(0)
print('line through zero {}'.format(line_through_zero(1)(x))) # only slope and x

给出

line through zero [-4, -3, -2, -1, 0, 1, 2, 3]

因此,柯里化的优势在于您可以获得具有固定参数的专用函数,并且可以使用这些函数而不是编写更通用的形式并在每次调用时设置固定参数.

So the advantage of currying is that you get specialized functions that have fixed parameters and can be used instead of writing the more general form and setting the parameters fixed at each single call.

柯里化的替代方法是:partiallambda默认参数.所以在实践中柯里化可能很有用,但如果你愿意,你也可以绕过它.

Alternatives to currying are: partial, lambda and default parameters. So in practice currying might be useful but you can also get around it if you want.

另见在 Python 中柯里化