在 Python 中重复函数组合 n 次,如 Haskell 的重复

Repeat a function composition n times in Python like Haskell's repeat

此代码无效:

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
'''

如何以更 Pythonic 的方式或 lambda 演算的方式编写它?

在递归情况下,您仍然需要 return 一个函数,而不是调用 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 <b>lambda x:</b> f (repeat(f, n-1)<b>(x)</b>)

如果你也定义一个复合函数,阅读起来会更容易一些:

def identity(x):
    return x


def compose(f, g):
    return lambda x: f(g(x))


# repeat :: (a -> a) -> Integer -> (a -> a)
# repeat _ 0 = id
# repeat f n = f . repeat f (n - 1)
def repeat(f, n):
    if n == 0:
        return identity
    else:
        return compose(f, repeat(f, (n-1)))

或使用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)