2

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 Answers 2

2

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))))))
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Made the changes as suggested and it now works!
You're welcome. The important bit is for you to understand why it works :).
@MohamedNabassoua, if that's all you might consider accepting an answer.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.