Why doesnt my code end

115 views Asked by At

it suppose to be function composition. I think that the problem is when there is only one function left in funcs. I wanted it to be an empty tuple but it didn't recognize it like that and enters an infinity loop

Thank you! :)

def compose(*funcs):
    if len(funcs)==0:
        return lambda x:x
    f=funcs[0]
    return lambda x: f(compose(funcs[1:])(x))
1

There are 1 answers

2
Max Noel On

Your compose function is defined to use *args. Which means that when called in your lambda expression, it always takes one argument and the funcs list is never empty. Which is why it recurses endlessly.

You want to either change the definition to def compose(funcs) (recommended), or call it with compose(*funcs[1:]).