在Python中像Haskell的重复一样重复一个函数组合n次

问题描述 投票:0回答:2

此代码无效:

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演算的方式编写它?

python function recursion repeat function-composition
2个回答
2
投票

在递归的情况下,您仍然需要返回一个函数,而不是调用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))

如果您还定义了合成功能,则阅读起来会更容易一些:

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)

0
投票

解决它的一个小方法是替换

return f( repeat(f, n - 1 ) )

with

return lambda x: f( repeat(f, n - 1 )(x) )
© www.soinside.com 2019 - 2024. All rights reserved.