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