Re: recursion performance



On Tue, 29 Nov 2005 14:35:47 -0800, 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) ) ) ) ) )

This exercise looks like an adaptation of Exercise 1.9 in SICP, shown
here:
http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-4.html#%_toc_%_sec_1.2.1

I recommend reading the treatment in the enclosing Section 1.2.1, "Linear
Recursion and Iteration", as linked above, with the following adaptation
of the two examples to CL:

Each of the following two procedures defines a method [sic] for adding two
positive integers in terms of the procedures 1+, which increments its
argument by 1, and 1-, which decrements its argument by 1.

(defun our-+ (a b)
(if (= a 0)
b
(1+ (our-+ (1- a) b))))

(defun our-+ (a b)
(if (= a 0)
b
(our-+ (1- a) (1+ b))))

I hope that clarifies what your book's author seems to be introducing.

--
Stephen Compall
Email: My username is s11. My domain is member..org, but insert the
abbreviation for `Free Software Foundation' between the dots.

.



Relevant Pages

  • Re: The Weakness of Lisp
    ... Also, we'll have to add the usual int bool equalities, that don't ... Might be a good exercise to completely implement that foreign operator ...
    (comp.lang.lisp)
  • Re: Why is Monday day 0?
    ... > CPU cycles! ... I'll leave 23:59:60 as an exercise for the reader. ... (defun m (f) ...
    (comp.lang.lisp)
  • Re: Hello World
    ... It unrolls the loop for 2,3,5 because ... (defun prime (number) ... ((zerop (rem number 2)) ...
    (comp.lang.lisp)
  • Re: "Higher Order Perl" book and Lisp
    ... >> This one is only slightly harder: Among the printed representations ... > Hmmm... ... > (defun f(n) ... (if (zerop n) ...
    (comp.lang.lisp)
  • Re: recursion performance
    ... (defun our+ (n m) ... ((zerop m) ... What is tail recursion? ...
    (comp.lang.lisp)