Re: recursion performance



zion_zii wrote:
Im just starting to program in lisp so please bear with me. As an
exercise, I was supposed to write the + function for 2
integers(symbols). This is what I wrote

(defun our+  (n  m)
  (cond
    ( (zerop  m)  n)
    (t  (+  (1+  n)  (1-  m) ) ) ) )

The suggested answer is as follows.

(defun our-add ( n  m)
  (cond
    ( (zerop m)   n)
    (t  (1+   (our-add  n  (1-  m) ) ) ) ) )

My question is this: Is there any difference in performance between the
first and the second?
Granted, I want to follow what the author has deemed accurate but I
dont want to do so blindly.  Thanks in advance.

AFAI can see, the suggested version decrements m first (all the way through) and then leaves the recursion, adding the 1 m times.


Your version decrements m and increments n immediately, and then goes on to add them -- wait, your code doesn't recur, i.e. use "our+", but it uses "+". So you're cheating ;)

If you use "our+" instead of "+" the operations are basically the same, but happen in a different order.

Another difference is that the suggested version is recursing, while your version would be tail-recursive, i.e. running in constant space and possibly faster, AFAI can see right now.

Just keep in mind to separate builtin math from the kind of math you're doing here, i.e. don't cheat using builtin "+".

--
The road to hell is paved with good intentions.
.



Relevant Pages

  • Re: recursion performance
    ... (cond ((zerop m) ... But 1+ is a tail call. ... The parameters to our+ can also be evaluated directly (no recursion), and our+ is again in tail position. ...
    (comp.lang.lisp)
  • Re: recursion performance
    ... (cond ((zerop m) ... about Lisp because you can do exactly the same exercise in any programming language that supports recursive calls. ... It's no wonder that the OP feels confused because the suggested answer is confusing. ...
    (comp.lang.lisp)
  • Re: trouble learning LISP
    ... (cond ((atom tree) ... I want to see the recursion as it occurs. ... (flatten (cdr tree))))))) ...
    (comp.lang.lisp)
  • Re: Translate this!
    ... (define (testif one two three four) ... (if (zerop one) ... I turned off the optimizations because I'm trying to debug the control ...
    (comp.lang.lisp)
  • Re: recursion performance
    ... (defun our+ (n m) ... ((zerop m) ... What is tail recursion? ...
    (comp.lang.lisp)