我很难在python中创建一个高阶函数,它将函数f,n次应用于生成一个新函数h,作为它的返回值。
def compile(f, n)
# h is a function, f applied n times
...
return h
new = compile(lambda x: 2*x, 3)
new(4) == 32 # new(4) == 2(2(2(4)))发布于 2018-05-31 02:44:40
因为Python的函数是一流的公民,所以函数本身可以定义一个新函数并返回它。在函数中定义函数可以用def完成,就像在您的顶级范围内一样。
作为一个副词,我建议您不要使用compile作为函数名,因为它不能准确地反映您想要做的事情,这称为函数组合,以及覆盖内置函数compile。
def compose_with_self(f, n):
def composed(arg):
for _ in range(n):
arg = f(arg)
return arg
return composed示例:
def add_one(x):
return x + 1
add_three = compose_with_self(add_one, 3)
print(add_three(1)) # 4发布于 2018-05-31 16:05:47
您可以使用递归轻松地完成这一任务。
n为零,只需返回xn至少为1,将f(x)应用于递归结果compile (f, n - 1)。我们可以轻松地用Python对其进行编码。
def compile (f, n):
return lambda x: \
x if n is 0 else compile (f, n - 1) (f (x))
double_thrice = compile (lambda x: 2 * x, 3)
print (double_thrice (4))
# 32https://stackoverflow.com/questions/50615723
复制相似问题