在Python中重复函数组合n次,如Haskell';重复一遍
此代码不起作用:在Python中重复函数组合n次,如Haskell';重复一遍,python,function,recursion,repeat,function-composition,Python,Function,Recursion,Repeat,Function Composition,此代码不起作用: def inc(x): return x + 1 def repeat(f, n): if n == 0: return lambda x: x else: return f( repeat(f, n - 1 ) ) inc_10 = repeat(inc, 10) #TypeError: unsupported operand type(s) for +: 'function' and 'int' ''' #
def inc(x):
return x + 1
def repeat(f, n):
if n == 0:
return lambda x: x
else:
return f( repeat(f, n - 1 ) )
inc_10 = repeat(inc, 10)
#TypeError: unsupported operand type(s) for +: 'function' and 'int'
'''
# Ideally
print(inc_10(0))
# 10
'''
我怎样才能用更具python风格的方式或lambda演算的方式来编写它呢?在递归情况下,您仍然需要返回一个函数,而不是调用
f
的结果
# repeat :: (a -> a) -> Integer -> a -> a
# repeat _ 0 = id
# repeat f n = \x -> f (repeat f (n-1) x)
def repeat(f, n):
if n == 0:
return lambda x: x
else:
return lambda x: f (repeat(f, n-1)(x))
或者使用functools.reduce
:
# repeat :: (a -> a) -> Integer -> (a -> a)
# repeat f n = foldr (.) id $ replicate n f
def repeat(f, n):
return reduce(compose, [f]*n, identity)
在
重复(f,n-1)(x)
时如何处理x
?这是什么样的语法?它只是常规的函数调用语法:repeat
返回一个函数,然后我将该函数应用于x
。我认为Python的标识只被称为id
,如果我没有弄错的话,id
返回任何对象的唯一对象标识符;这不是身份功能。
# repeat :: (a -> a) -> Integer -> (a -> a)
# repeat f n = foldr (.) id $ replicate n f
def repeat(f, n):
return reduce(compose, [f]*n, identity)