如何从高阶函数返回值?

时间:2020-05-01 14:39:41

标签: python-3.x function higher-order-functions

请问我该怎么做,以便调用make_repeater(square,0)(5)返回5而不是25?我猜想我需要更改“ function_successor = h”行,因为那样我就只能得到square(5),但是不确定我需要将其更改为...

square = lambda x: x * x

def compose1(h, g):
    """Return a function f, such that f(x) = h(g(x))."""
    def f(x):
        return h(g(x))
    return f

def make_repeater(h, n):
    iterations = 1
    function_successor = h
    while iterations < n:  
        function_successor = compose1(h, function_successor)
        iterations += 1
    return function_successor

它需要满足许多其他要求,例如:

make_repeater(square,2)(5)= square(square(5))= 625

make_repeater(square,4)(5)= square(square(square(square(5()))))= 152587890625

1 个答案:

答案 0 :(得分:0)

要实现这一点,您必须使用身份函数(f(x) = x)作为function_successor的初始值:

def compose1(h, g):
    """Return a function f, such that f(x) = h(g(x))."""
    def f(x):
        return h(g(x))
    return f


IDENTITY_FUNCTION = lambda x: x

def make_repeater(function, n):
    function_successor = IDENTITY_FUNCTION

    # simplified loop
    for i in range(n):
        function_successor = compose1(function, function_successor)

    return function_successor


if __name__ == "__main__":    
    square = lambda x: x * x
    print(make_repeater(square, 0)(5))
    print(make_repeater(square, 2)(5))
    print(make_repeater(square, 4)(5))

输出为

5
625
152587890625

这并不是最优化的性能,因为身份函数(它没有做任何有用的事情)始终是组合函数的一部分,因此优化版本如下所示:

def make_repeater(function, n):
    if n <= 0:
        return IDENTITY_FUNCTION

    function_successor = function
    for i in range(n - 1):
        function_successor = compose1(function, function_successor)

    return function_successor