[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.lisp

fibonacci sequence using iterative process in SICP, cannot completely understand

chong.franklin

2/28/2016 6:41:00 PM

Here is an iterative example of a procedure computing the fibonacci sequence in SICP. The idea is:

a = fib(n+1) = a+b

b = fib(n) = a

(define (fib n)
(fib-iter 1 0 n))
(define (fib-iter a b count)
(if (= count 0)
b
(fib-iter (+ a b) a (- count 1))))

Looking at it deeper, I don't understand why continuing the computation towards fib(n+1) is necessary. I found we could have written.

;; a and b are first and second integers respectively
;; in the recursive call, b would be replaced by a+b because it is the next number in the sequence
;; so now a will be replaced by the previous value of b because it is the previous value.
(define (fib2 n)
(fib-iter 1 0 n))
(define (fib-iter a b count)
(if (= count 0)
b
(fib-iter b (+ a b) (- count 1))))

Now, I really think the first example, the one continuing up to n+1 is really redundant. I don't understand why is that necessary. What's wrong with my proposed iterative example?
2 Answers

William James

2/28/2016 10:24:00 PM

0

franklin wrote:

>
> (define (fib n)
> (fib-iter 1 0 n))
> (define (fib-iter a b count)
> (if (= count 0)
> b
> (fib-iter (+ a b) a (- count 1))))

(define (fib n)
(let loop ((n n) (a 0) (b 1))
(if (zero? n)
a
(loop (- n 1) b (+ a b)))))

--
The report card by the American Society of Civil Engineers showed the national
infrastructure a single grade above failure, a step from declining to the point
where everyday things simply stop working the way people expect them to. ---
washingtonpost.com/local/trafficandcommuting/us-infrastructure-gets-d-in-annual-report/2013/03/19/c48cb010-900b-11e2-9cfd-36d6c9b5d7ad_story.html

Paul Rubin

2/28/2016 11:20:00 PM

0

franklin <chong.franklin@gmail.com> writes:
> I really think the first example, the one continuing up to n+1 is
> really redundant. I don't understand why is that necessary. What's
> wrong with my proposed iterative example?

I don't see the redundancy: both functions work and seem to do the
exact same amount of arithmetic.