Search code examples
common-lispstack-overflowfranz-lisp

Function call stack overflow


I get the error message below when I run my code. The code below add the elements that are not nil.

(summit2 '(0 nil 1 2))

Error: Received signal number -3 (function call stack overflow (delayed response))
[condition type: ASYNCHRONOUS-OPERATING-SYSTEM-SIGNAL]

I have tried changing null with nil. I also tried using eq as opposed to eql.

(defun summit2 (lst)
    (if (eql (car lst) null)
        (summit2 (cdr lst))
      (+ (car lst) (summit2 (cdr lst)))))

the expected output should be 3, the sum of the elements in the list that are not nil


Solution

  • First of all, the check for nil should be done by using the NULL function, so (null (car lst)) in your case. Secondly, your recursion lacks the base case (the error you're getting indicates a stack overflow due to infinite recursion). Now you only distinguish between whether the next element is nil or non-nil. You need a third case to handle the empty list. This suggests the use of COND. You could, for example do something like:

    (defun summit2 (lst)
      (cond 
        ((null lst)
         0)
        ((null (car lst))
         (summit2 (cdr lst)))
        (t
         (+ (car lst) (summit2 (cdr lst))))))