Recursion vs. Iteration


; Recursive Fibonacci numbers
(define (fib n)
  (cond ((= n 0) 0)
        ((= n 1) 1)
        (else (+ (fib (- n 1))
                 (fib (- n 2)))) ) )


; Tail-recursive Fibonacci using helper function
(define (fibon n)
   (fib-h n 0 0 1))

(define (fib-h goal current fib-current fib-next) (if (= goal current) fib-current (fib-h goal (1+ current) fib-next (+ fib-current fib-next))))


; Iterative Fibonacci
(define (fibonacci n)
  (let ((lastfib 0) (thisfib 1) (nextfib 0))
    (dotimes (i n lastfib)
      (set! nextfib (+ lastfib thisfib))
      (set! lastfib thisfib)
      (set! thisfib nextfib) ) ))

Contents    Page-10    Prev    Next    Page+10    Index