Subject: Re: Tail Recursive version of fibonacci
From: rpw3@rigden.engr.sgi.com (Rob Warnock)
Date: 1998/12/19
Newsgroups: comp.lang.scheme
Message-ID: <75f46l$4gm9g@fido.engr.sgi.com>
Moshe Zadka  <moshez@math.huji.ac.il> wrote:
+---------------
| Someone asked  here how to do a tail-recursive version of fibonnaci
| (in the traditional style, I suppose, not using the 1/sqrt(5) trick).
| Here it is:
|    (define (fib-n-from-2 a b n) 
|      (if (= n 0) 
|          a 
|          (fib-n-from-2 b (+ a b) (- n 1))))
|    (define (fib n) (fib-n-from-2 0 1 n))
+---------------

Hmmm... Seems to me that needlessly computes the N+1'st number (which in
the case of large "n" could be a large bignum) and then throws it away.
By returning "b" and adjusting the base case to match, you can avoid that:

    (define (fib n)
      (define (fib/iter a b n)
	(if (zero? n)
	  b
	  (fib/iter b (+ a b) (- n 1))))
      (cond
	((or (negative? n) (not (integer? n)) (not (exact? n)))
	 (error "fib: domain error: need non-negative exact integer, got:" n))
	((< n 2) n)
	(else (fib/iter 0 1 (- n 1)))))


-Rob

-----
Rob Warnock, 8L-855		rpw3@sgi.com
Applied Networking		http://reality.sgi.com/rpw3/
Silicon Graphics, Inc.		Phone: 650-933-1673
2011 N. Shoreline Blvd.		FAX: 650-964-0811
Mountain View, CA  94043	PP-ASEL-IA