next up previous
Next: 7 Iteration and Recursion Up: 6 Analyzing Algorithms Previous: 6.1 Recursive Fibonacci

6.2 Tail-Recursive Fibonacci

Introductory computer science texts [Abe 85,Spr 89] give tail-recursive definitions for the fibonacci function.

fib_iter =: monad define 'fib_iter_helper 1 0 , y.'

fib_iter_helper =: monad define script
('a' ; 'b' ; 'count') =. y.
if. count = 0
  do. b
  else. fib_iter_helper (a + b) , a , count - 1
end.
)

fib_iter makes a single call to fib_iter_helper to compute fibonacci. fib_iter_helper is tail-recursive since the continuation of the one recursive call is the identity function.


next up previous
Next: 7 Iteration and Recursion Up: 6 Analyzing Algorithms Previous: 6.1 Recursive Fibonacci
2002-11-26