Fibonacci sequence in Haskell

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

Mathematical definition of the fibonacci sequence

The above picture illustrates cialis us drugstore. 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)


$ ghci fibonacci.hs
[1 of 1] Compiling Main             ( fibonacci.hs, interpreted )
Ok, modules loaded: Main.
*Main> fibonacci 0
*Main> fibonacci 1
*Main> fibonacci 10
*Main> map fibonacci [0..20]
*Main> fibonacci -1

    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.

This entry was posted in Haskell and tagged , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?