What would happen if I were to define the following procedure in Lisp: (define (p) (p)) What value would it return? I'm not new to programming but I'm reading this book that's kinda more in depth and uses Lisp for the examples and this one has got me confused.
Asked
Active
Viewed 325 times
1
-
The same as: "10 GOTO 10" – coredump Jul 03 '17 at 19:32
-
Is there any reason to suppose it's different from something like `int foo() { return foo(); }` in C or Java (tail-call optimization aside)? – Joshua Taylor Jul 06 '17 at 21:55
1 Answers
6
When executed, the procedure will create an infinite loop and it will never return a value. We're defining a recursive procedure called p
whose body is a call to itself; because there is no base case, the procedure will never end. In a more familiar syntax (say, Python's) it's the same as this:
def p():
return p()
Your procedure is being called in tail position, which Scheme can optimize to use a constant amount of space - whereas the Python interpreter can't do that optimization and will quickly crash due to a stack overflow.

Óscar López
- 232,561
- 37
- 312
- 386
-
2Depending on the Lisp implementation (interpreter or high debug settings) there might be a stack overflow, too. Scheme requires TCO to be supported by an implementation, interpreter or compiler. Lisp does not. – Rainer Joswig Jul 03 '17 at 09:37