📜  Python中的柯里化函数

📅  最后修改于: 2022-05-13 01:54:58.611000             🧑  作者: Mango

Python中的柯里化函数

在问题解决和函数式编程中, currying是一种简化函数执行的实践,该函数接受多个参数来执行顺序的单参数函数。简单来说,Currying 用于通过评估函数参数的增量嵌套,将多参数函数转换为单参数函数。柯里化还将一个论点修正为另一个论点,从而在执行时形成一种相对模式。

柯里化的数学说明:
通常,函数的柯里化将任意数量的计算和数据占用到返回预期输出的单个实函数中。我们在这里采取,

f(x, y) = (x*x*x) + (y*y*y)
h(x) = (x*x*x)
h(y) = (y*y*y)
h(x)(y) = h(x)+h(y)
f(x, y) = h(x)(y)
Curry f = h(x)(y)

例如,我们将链式组合函数。

a(x) = b(c(d(x)))

def change(b, c, d):
    def a(x):
        return b(c(d(x)))
    return a

v(a, b, c, d, e) = w(x(y(z(a, b, c, d, e))))

# Currying in Python - Many to Single Argument
 def change(a):
    def w(b):
        def x(c):
            def y(d):
                def z(e):
                    print(a, b, c, d, e)
                return z
            return y
        return x
    return w
   
change(10)(20)(30)(40)(50)

输出:

10 20 30 40 50

在这里,概念是将一个函数嵌套到另一个函数,因此一个函数的结果会记录在函数链中。通过将一个巨大的操作块简化为更简单的顺序块。

代码 #1:将公里改为米,将米改为厘米。

# Demonstrate Currying of composition of function
def change(b, c, d):
    def a(x):
        return b(c(d(x)))
    return a
      
def kilometer2meter(dist): 
    """ Function that converts km to m. """
    return dist * 1000
      
def meter2centimeter(dist): 
    """ Function that converts m to cm. """
    return dist * 100
      
def centimeter2feet(dist):
    """ Function that converts cm to ft. """
    return dist / 30.48
      
if __name__ == '__main__':
    transform = change(centimeter2feet, meter2centimeter, kilometer2meter )
    e = transform(565)
    print(e)
     

输出:

1853674.5406824148


代码#2:

# Demonstrate Currying of composition of function
  
def change(b, c, d):
    def a(x):
        return b(c(d(x)))
    return a
      
def daystohour(time): 
    """ Function that converts days to hours. """
    return time * 24
      
def hourstominutes(time): 
    """ Function that converts hours to minutes. """
    return time * 60
      
def minutestoseconds(time):
    """ Function that converts minutes to seconds. """
    return time * 60
      
if __name__ == '__main__':
    transform = change(minutestoseconds, hourstominutes, daystohour)
    e = transform(10)
    print(e)
     

输出:

864000