O'Reilly logo

Haskell Cookbook by Yogesh Sajanikar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Open src/Main.hs in an editor. After the module definition, we will add the definition for our fibonacci number.
  2. Add the function declaration for fib. Let's assume that we have an infinite list of fibonacci numbers, fiblistFinding the nth fibonacci number in the list is easy using the List index function (!!):
        fib :: Int -> Integer        fib n = fiblist !! n
  1. Implement the function fiblist. The function fiblist is obviously a list of integers. Define fiblist as follows:
        fiblist :: [Integer]        fiblist = 0 : 1 : zipWith (+) fiblist (tail fiblist)
  1. This is an efficient implementation (O(n)) of the fibonacci number calculator. We can test it by calculating the 10000th fibonacci number:
        main :: IO ()        main = do         let fib10k = fib ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required