While learning about infinite list creation in Haskell I found the following implementation of fibonacci using higher order functions (zipWith
)
fibs :: [Integer]
fibs = 1:1:(zipWith (+) fibs (tail fibs))
Looks very clever but also too much abstraction for a beginner.
So, I decided to create the recursive solution of fibonacci that ended like this:
fib :: (Num a, Ord a) => a -> a
fib n
| (n == 0) = 1
| (n == 1) = 1
| (n > 1) = fib (n - 1) + fib (n - 2)
fib' :: (Num t, Ord t) => t -> [t]
fib' n = (fib n):(fib' (n+1))
fiblst :: [Integer]
fiblst = fib' 0
Both works, but I see really bad performance in my implementation, while the original (fibs
) function goes at the speed of light and keeps printing the whole screen, mine (fiblst
) on the other side hardly goes to the third line and keeps eating the CPU.
Any hints about why my implementation is so slow compared to the other ?
Thanks