在 python 中获取高阶函数的输入

Get the input of an Higher order function in python

假设我有一个 HOF

def some_func(lst):
    def func(args):
        if args[0]=='compute':
            return sum(lst)
        elif args[0]=='add':
            XXXXX  #Return a new HOF with the 2 sub HOF input parameters added together.  
    return func
x1=some_func([1,2,3])
x2=some_func([2,3,4])

HOF 的输入 *args 之一是 ('add', another_hof),它要求 HOF 添加另一个 HOF 参数和 return 一个添加了参数的 HOF。

示例:

x3=x1('add',x2)
x4=some_func([3,5,7])

然后,

x3 should equal x4.
test_case: 
x1=some_func([1,2,3])
x2=some_func([2,3,4])
x1('compute')=6
x2('compute')=9
x3=x1('add',x2)
x3('compute')=15

当我在函数 func(*args)?

中执行 x HOF ('add,x2) for x1 function, is possible me to know the x2' 输入参数 [2,3,4]

如我所见,问题的核心是:给定对 func 实例的引用,您需要获取它包含的 lst 值。

一种方法是向您的条件块添加另一种模式,即 returns lst。我们称它为 get_lst:

def some_func(lst):
    def func(*args):
        if args[0]=='compute':
            return sum(lst)
        elif args[0]=='add':
            new_lst = [a+b for a,b in zip(lst, args[1]("get_lst"))]
            return some_func(new_lst)
        elif args[0] == "get_lst":
            return lst
    return func

x1=some_func([1,2,3])
x2=some_func([2,3,4])
print(x1('compute'))
print(x2('compute'))
x3=x1('add',x2)
print(x3('compute'))

结果:

6
9
15

您还可以将 lst 分配给函数对象的属性:

def some_func(lst):
    def func(*args):
        if args[0]=='compute':
            return sum(lst)
        elif args[0]=='add':
            new_lst = [a+b for a,b in zip(lst, args[1].params)]
            return some_func(new_lst)
    func.params = lst
    return func

x1=some_func([1,2,3])
x2=some_func([2,3,4])
print(x1('compute'))
print(x2('compute'))
x3=x1('add',x2)
print(x3('compute'))