Jan 28, 2008

Tail recursion of Scheme.

Ruby program for Fibonacci number.


def fib(n)
if n < 2
n
else
fib(n - 2) + fib(n - 1)
end
end



Scheme program for Fibonacci number.


(define (fib n)
(if (< n 2)
n
(+ (fib (- n 1)) (fib (- n 2)))))



Tail recursion version.


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


Scheme has "tail recursion optimization".
Then Scheme is faster than Ruby with optimization.

No comments: