BurnedOut
BurnedOut

Reputation: 1

Recursive Addition in Lisp

I'm a beginner and I am trying to teach myself Common Lisp and during my self-study I have written a function that I believe should work for recursive addition of two arguments. However, the function always fails. Why is that?

(defun sum (n m)
  ;;;Returns the sum of n and m using recursion
  (cond ((eq m 0) n))
  (sum (1+ n) (1- m)))

As I understand it, it should continually add 1 to n while decrementing m until m is 0 at which point, the recursive addition is complete

Upvotes: 0

Views: 1284

Answers (2)

sheikh_anton
sheikh_anton

Reputation: 3452

It's really wierd use case to do such addition, but I'll explain you where is your mistakes:

(defun sum (n m)
  ;;;Returns the sum of n and m using recursion
  (cond ((eq m 0) n)) ;; <= This line is ignored, you not returnin N.
  (sum (1+ n) (1- m))) ;; <= this will be called forever

You should write:

(defun sum (n m)
  "Recursively increment N and decrement M untill M = 0"
  (if (= m 0) ;; don't use EQ for numbers, use EQL or =.
    n
    (sum (1+ n) (1- m)))) ;; Otherwise recursive call

Let's trace it to see how it works:

CL-USER> (sum 0 10) 
  0: (SUM 0 10)
    1: (SUM 1 9)
      2: (SUM 2 8)
        3: (SUM 3 7)
          4: (SUM 4 6)
            5: (SUM 5 5)
              6: (SUM 6 4)
                7: (SUM 7 3)
                  8: (SUM 8 2)
                    9: (SUM 9 1)
                      10: (SUM 10 0)
                      10: SUM returned 10
                    9: SUM returned 10
                  8: SUM returned 10
                7: SUM returned 10
              6: SUM returned 10
            5: SUM returned 10
          4: SUM returned 10
        3: SUM returned 10
      2: SUM returned 10
    1: SUM returned 10
  0: SUM returned 10
10

If you'll take an advice - don't try to do such weird things with recursion, if you want to leard how to use it, try it for some natural-recursive cases like factorials, fibonacci, tree processing and such.

Upvotes: 5

uselpa
uselpa

Reputation: 18917

I think you have 2 simple typos:

  1. one parenthesis too many and
  2. missing t in your cond clause.

What you probably meant was:

(defun sum (n m)
  (cond 
   ((eq m 0) n)               ; here you had one parenthesis too many
   (t (sum (1+ n) (1- m)))))  ; here you were missing the `t` symbol

Upvotes: 5

Related Questions