Recursive function using lambda, why doesn't this work?

I have a function that does some calculation, g (x). Now I want to write a function that computes g (g (g (... g (x)))), where g is applied n times. I tried to do this using repeat_fn(see below), but this will not work.

According to a Recursive function using a lambda expression , the solution is to use functools.partial. It really works, but I don’t understand how to do it. Also, I don't understand why my approach is not working.

g = lambda x: 2*x

# Function that returns the fˆn map
def repeat_fn(f, n):
     if n == 1:
         return f
    else:
        return lambda y: f( repeat_fn(f(y), n-1) )


 def repeat_fn_base(fn, n, x):
    if n == 1:
        return fn(x)
    else:
        return fn(repeat_fn_base(fn, n-1, x))

def repeat_fn2(fn, n):
    return functools.partial(repeat_fn_base, fn, n)


j = repeat_fn2(g, 5)
print(type(j))
print(j(2))

k = repeat_fn(g, 5)
print(type(k))
print(k(2))

, repeat_fn , k = repeat_fn(g, 5), , . -, , k . print(k(2)) : TypeError: unsupported operand type(s) for *: 'int' and 'function'.

, , , h = g(g(x) .

- ? !

+6
2

return lambda y: f( repeat_fn(f(y), n-1) ) repeat_fn f, f(y), .. . f, fn_repeat () f(y) ( ).

def repeat_fn(f, n):
    if n == 1:
         return f
    else:
        return lambda y: repeat_fn(f, n-1)(f(y))

k = repeat_fn(lambda x: 2*x, 5)
print(k(2))  # 64
+5

, ; :

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

def repeat_fn(f, n):
    if n == 1:
        return f
    else:
        return compose(f, repeat_fn(f, n - 1))

, repeat_fn n==0, identity = lambda x: x:

def repeat_fn(f, n):
    if n == 0:
        return identity
    else:
        return compose(f, repeat_fn(f, n - 1))

, compose(f, identity) == f.

+2

All Articles