Subject: Re: Benefits of tail recursion (was: Cost of Recursion)
From: Erik Naggum <>
Date: 2000/02/15
Newsgroups: comp.lang.lisp
Message-ID: <>

* Robert Munyer <>
| For me, a loop written with ITERATE is easier to read than the same loop
| written with DO.  With ITERATE, the process of computation has a more
| linear "flow" through the text of the function.  With DO, the step forms
| are interleaved with the initialization forms, which makes the flow of
| computation feel like it's been "scattered" all over the text of the
| function.

  what's keeping you from writing an ITERATE macro that expands into DO
  (or, rather, TAGBODY and GO forms)?  it should be eminently doable in the
  majority of cases where it is indeed only (tail-recursive) iteration.

| In summary: the next time you're programming a loop, and the code doesn't
| seem to "fit," try using recursion.  You might be surprised how well it
| works.

  there is no semantic difference between (PSETQ FOO X BAR Z) (GO TAG) and
  (ITERATOR :FOO X :BAR Z) as long as both "resolve" to tail recursion.
  (I'm using keyword arguments only to be explicit.)

| In fact, I think the whole concept of "iteration vs. recursion" is a
| wrong way to think, a left-over distinction from the days before we
| understood tail recursion.  I think it makes sense to think of a
| tail-recursive program as being both iterative AND recursive.

  I agree with you on this.

| Now, on to the example I promised earlier.  Below is a function I wrote a
| couple of years ago.  As I recall, I tried several times to write it with
| DO, and every time the code came out UGLY.  So I tried doing it with
| recursion, and it "just worked."  It was easier to write, and easier to
| read, and just as efficient as the version I wrote with DO.
| ; Returns INV such that (= (MOD (* NUMBER INV) MODULUS) (GCD NUMBER MODULUS)).
| ; Note that if NUMBER and MODULUS are relatively prime, the GCD is 1, and INV
| ; is the multiplicative inverse of NUMBER over the Galois field of MODULUS.
| (defun mod-inverse (number modulus)
|   (check-type number  (integer 1))
|   (check-type modulus (integer 1))
|   (iterate iter ((a modulus) (b number) (c 0) (d 1))
|     (multiple-value-bind (q r) (floor a b)
|       (cond ((plusp r) (iter b r d (- c (* q d)))) ; thanks Euclid!
|             ((minusp d) (+ d modulus))
|             (t d)))))

(do ((a modulus) (b number) (c 0) (d 1))
    ((multiple-value-bind (q r) (floor a b)
       (if (plusp r) (psetq a b b r c d d (- c (* q d))) t))
     (if (minusp d) (+ d modulus) d)))

  it _is_ unfortunate that DO et al were invented so long before multiple
  values that we sometimes have to expand out the forms manually.

  hope this helps.