1

I met a problem when practicing high order function. Function "repeated" and "repeated2" are of the same propose.

However, "repeated2" works and returns 8, while "repeated" fails: (this confused me a lot why variable'l' cannot be tracked, but variable 'n' seems work well)

def repeated(f, l):
    def h(x):
        while l:
            x=f(x)
            l=l-1
        return x
    return h

def repeated2(f, n):
    def h(x):
        k = 0
        while k < n:
            x, k = f(x), k + 1
        return x
    return h

result2=repeated2(lambda x:x+1,5)(3)
result=repeated(lambda x:x+1,5)(3)



Traceback (most recent call last):
  File "error_code.py", line 18, in <module>
    result=repeated(lambda x:x+1,5)(3)
  File "error_code.py", line 3, in h
    while l:
UnboundLocalError: local variable 'l' referenced before assignment
Eric Shen
  • 31
  • 3

0 Answers0