Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Can you please debug this lisp recursive function for me LINE BY LINE? (defun SA

ID: 3808361 • Letter: C

Question

Can you please debug this lisp recursive function for me LINE BY LINE?

(defun SAFE-SUM L)
   (if (endp L)
   0
   (let ((X (SAFE-SUM (CDR L))))
       (if (and (numbers (car L)) (numberp x))
           (+ (car L) X)
       ‘ERROR)))))

L = (4 1 6 3)
X = 10

I already know the answer. Just when I debug it on paper, I'm not following how the recursive function is being called. Is ((X (SAFE-SUM (cdr L)))) executed repeatedly first or after the first call, it executes the next lines and then call itself again? I'm kind of confused about that. Thank in advance.

Explanation / Answer

Recursion works like a stack.

It executes the function for the remaining list as soon as there is a call, everything is put on the stack .

When this call is completed, it returns to the function and then executes the next line.

So if there is a call releatedly, it will execute the innermost call first till the last line, then it will cone back to the function calling it, and so on until it reaches the very first call with the complete list.

Imagine a person keeping question-papers on left hand one by one, then distributing those. So the last question-paper kept on the stack is given out to the first student, and so on.

Similarly the last call gets executed first completely, then it returns to the second last call.

So in this case, it starts with

the first call with L = (4 1 6 3)

Then when there is a call with CDR of this L that is (4,6,3) it puts everything on the stack e.g. Program counter, current values of the variables and processes the inner call. This goes on repeatedly until Nil is reached. Then it comes back to the next lines of the first call only when all the inner recursive calls are completed.

Hope this explains.