Recursive subtraction does not work

197 views Asked by At

I wrote a function for recursive subtraction in lisp, but when i load it and run the function with numbers for example ( subtract 4 3 ) the output is -3 which I do not understand why.

(defun subtract (x y)
  (if (eq y 0) 
    x
    (- 1 (subtract x (- y 1) ) ) ) )
2

There are 2 answers

0
Michael Kohl On BEST ANSWER

Here's a fixed version of your code:

(defun subtract (x y)
  (if (zerop y) 
    x
    (subtract (1- x) (1- y))))

Notice that in the recursive call we subtract 1 from both x (to actually decrement the number) and y (to get it closer to the base case, 0).

0
Vatine On

First, don't use eq to compare numbers. It accidentally works in this case, because your numbers happen to be small. Either use =, or (since you're looking for zero) zerop.

Second, you can use (trace subtract) to see a trace of invocations and return values.

Third, (- 1 x) and (- x 1) have, in the general case, very different values.