Reputation: 693
I have the following function:
def lst(*l):
if l==():return None
else: return cons(l[0],lst(l[1:]))
When I run it, I get "maximum recursion depth exceeded in comparison". Curiously, when I add a warper which converts the parameter tuple into a list, everything works just fine:
def lst(*l):
return _lst(list(l))
def _lst(l):
if l==[]:return None
else: return (l[0],_lst(l[1:]))
>>> lst(1,2)
(1, (2, None))
What is the problem and how to deal with this strange behavior?
Upvotes: 3
Views: 230
Reputation: 6814
you are missing a * when passing the parameters again to the function
def lst(*l):
if l==():return None
else: return cons(l[0],lst(*l[1:]))
You are passing the empty tuple as a first positional parameter which means that in the next recursion l is actually equal to ((),) (a tuple containing one empty tuple) when it should be ()
Upvotes: 4