The fibonacci sequence has many applications , such asA�paintings , predicting stock market changes and even sunflowers. This example illustrates the fibonacci sequence in Haskell.

The above picture illustrates the mathematical definition of the fibonacci sequence and it is has very close resemblance to the Haskell code.

fibonacci :: Integer -> Integer fibonacci n | n == 0 = 0 | n == 1 = 1 | n > 1 = fibonacci (n-1) + fibonacci (n-2)

Output:

$ ghci fibonacci.hs [...] [1 of 1] Compiling Main ( fibonacci.hs, interpreted ) Ok, modules loaded: Main. *Main> fibonacci 0 0 *Main> fibonacci 1 1 *Main> fibonacci 10 55 *Main> map fibonacci [0..20] [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765] *Main> fibonacci -1 <interactive>:1:0: No instance for (Num (Integer -> Integer)) arising from a use of `-' at <interactive>:1:0-11 Possible fix: add an instance declaration for (Num (Integer -> Integer)) In the expression: fibonacci - 1 In the definition of `it': it = fibonacci - 1 *Main> :q Leaving GHCi.

As you can see the interpreter executes the fibonacci function for several inputs. Negative values are not allowed as input, hence the error message. The code used for calculating the fibonacci sequence is not optimal, it calculates the fibonacci numbers multiple times.