1

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.

coredump
  • 37,664
  • 5
  • 43
  • 77
I.Ilieva
  • 11
  • 1

1 Answers1

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
  • 2
    Depending 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