Friday, March 22, 2013

Tail recursive fibonacci

Tail recursive fibonacci is similar to a fibonacci using Seq.unfold
let fibonacci n =
  let rec tailRecursiveFibonacci n accum'next accum =
    if n <= 0 then
      accum
    else
      tailRecursiveFibonacci (n - 1) (accum + accum'next) accum'next
  tailRecursiveFibonacci n 1L 0L

> fibonacci 0;;
val it : int64 = 0L
> fibonacci 1;;
val it : int64 = 1L
> fibonacci 2;;
val it : int64 = 1L
> fibonacci 3;;
val it : int64 = 2L
> fibonacci 4;;
val it : int64 = 3L
> fibonacci 5;;
val it : int64 = 5L
> fibonacci 6;;
val it : int64 = 8L

If you want to fibonacci sequence itself, you should use Seq.unfold way. But if you want Fib(n) value directly, you should this tail recursive fibonacci.

No comments:

Post a Comment