2
votes

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

2

2 Answers

2
votes

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))))))
2
votes

Some remarks

  • You can spell your list list, there is no need to abbreviate it to lst.
  • All branches in your code leads to a recursive call to summit, there is no case where you stop computing the result. This infinite computation takes up stack space, which is why it eventually stops with a stack overflow.
  • Please indent your code in a conventional way (read for example this style guide)

Notice that the case where an element is nil is not much different than the case where the input list is empty. With the following code, both are handled the same way:

(defun sum (val)
  (if (consp val)
      (+ (sum (car val))
         (sum (cdr val)))
      (or val 0)))

This also means the code is able to do more than expected, i.e. you can sum numbers in a tree:

(sum '(0 1 2 nil 4 5 7 (1 2)))
=> 22

And it also works when the input is just an number:

(sum 5)
=> 5