1

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))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Hila
  • 11
  • 2

1 Answers1

6

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:]).

Max Noel
  • 8,810
  • 1
  • 27
  • 35
  • However I'm not sure I understood currectly, why does the funcs list is never empty..? – Hila Dec 15 '13 at 20:16
  • Because of `*args`. When you define a function such as `def compose(*args)` and call it with `compose(funcs[1:])`, the `args` variable becomes `(funcs[1:],)`, which means that it's never empty. If `funcs[1:]` is an empty list, `args = ([],)`. That is, a tuple containing one element (which is an empty list). See http://stackoverflow.com/questions/3394835/args-and-kwargs for more info on `*args` and `**kwargs`. – Max Noel Dec 15 '13 at 22:33