3

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?

3
  • Can you post the code that actually works, too? Commented Apr 18, 2014 at 16:19
  • 1
    Replace if l==():return None with if not l: return None. Also, what does cons do? You might be able to replace this with reduce. Commented Apr 18, 2014 at 16:21
  • Thanks for your advice, @IceArdor. cons is a constructor like that: def __init__(self,car,cdr):self.car=car;self.cdr=cdr. I tried to replace the recursion with reduce, but something went wrong (seems like reduce works "wrong" direction) and I have absolutely no idea how to get it the right way. As long as i have a working code, thanks to Samy Arous, I wish not to make it broken. Thank you anyway. Commented Apr 18, 2014 at 16:47

1 Answer 1

4

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 ()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.