1

So I am new to lisp, and I am quite confused about the problem I have:

(defun factorial (x)
  (if (>= x 1)
      (* x (factorial (- x 1)))
      1))

The factorial function can output 3000! without a problem, however

(defun sum (x)
  (if (<= x 1)
      1
      (+ x (sum (- x 1)))))

Stack overflows at (sum 10000), I am using clisp.

Could anyone please clarify why this is happening?

7
  • Not sure, but it could be a syntax error - should there be a space between sum and (- x 1)? Commented Mar 19, 2014 at 18:36
  • 1
    Would be prettier, but it's not an error :/. I'm quite unsure why this is happening, could it be that lisp has a maximum amount of recursive calls it can do? Commented Mar 19, 2014 at 18:37
  • That's definitely true; if your interpreter doesn't optimize for tail recursion, you're going to have a really tall stack. What number are you passing the function? This is just a re-implementation of factorial, right? Commented Mar 19, 2014 at 18:41
  • Yeah, I was messing about with basic functions like that, I was passing (factorial 5000) and (sum 5000) which worked fine, however going to (sum 6000) it no longer works and it stack overflows, how would I fix that? Commented Mar 19, 2014 at 18:43
  • 1
    @jstaab Even if an implementation optimizes tail calls, these functions aren't written in a way where that would be applicable. Each stack frame needs to remain active until the recursive call returns so that the arithmetic operation can be performed. (A very smart compiler might figure out a way to optimize this, perhaps a la tail recursion modulo cons.) Commented Mar 19, 2014 at 21:05

1 Answer 1

3

Your functions are not tail-recursive, so the compiler (and interpreter) increase stack for each iteration, eventually running out of it.

Your options are enumerated in FAQ How do I avoid stack overflow?; the relevant are:

  1. Compile the functions
  2. Increase Lisp stack size
  3. Rewrite using iteration instead of recursion
  4. Rewrite using tail-recursion and compile
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.