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. The file will define the Main module with the function main :: IO ()
  2. Here is the module definition. Add declaration of our function, fib. The function takes an integer to denote the index of the fibonacci number and returns the fibonacci number at the given index:
        fib :: Integer -> Integer
  1. Handle the base cases using pattern matching and pattern guards. We have three cases:
  • Case I--Index is negative. This is an error case:
        fib n | n < 0 = error "invalid index"
  • Case II--Index is zero. We provide the 0th value as a seed value:
        fib 0 = 0
  • Case III-- Index is one. We provide the 1st value as the seed value:
        fib 1 = 1
  1. Handle the generic case, that is, calculate the nth fibonacci number from the  ...

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