[Haskell-cafe] Fibbonachi numbers algorithm work TOO slow.

Felipe Lessa felipe.lessa at gmail.com
Mon Nov 5 17:49:14 EST 2007


> For a more efficient Haskell implementation of fibonacci numbers, try
>
> fibs :: [Integer]
> fibs = 1 : 1 : zipWith (+) fibs (tail fibs)
>
> fib n = fibs !! n

This is uglier, but just to keep using just plain recursion:

fib = fib' 0 1
  where
    fib' a b 0 = a
    fib' a b n = fib' b (a+b) (n-1)

You may want "fib' a b n | a `seq` b `seq` n `seq` False = undefined"
for strictness if the compiler isn't smart enough to figure out
(sorry, didn't test it).

And, *please* correct me if I said something stupid =).

See ya,

-- 
Felipe.


More information about the Haskell-Cafe mailing list