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

前端 未结 1 1185
野性不改
野性不改 2021-01-25 12:30

This code does NOT work:

def inc(x):
    return x + 1

def repeat(f, n):
    if n == 0:
        return lambda x: x
    else:
        return f( repeat(f, n - 1 )          


        
1条回答
  •  北海茫月
    2021-01-25 13:22

    You still need to return a function, not the result of calling f, in the recursive case.

    # 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))

    It's a little easier to read if you define a composition function as well:

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

    Or using 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 讨论(0)
提交回复
热议问题