Fibonacci numbers in Haskell
Example for versions
GHC 6.10.4
This example uses one of the main Haskell features — lazy evaluations and infinite lists. Infinite list of Fibonacci numbers fibs
is defined using zipWith
function which applies its first argument (a function of two variables, in this case +
) to pairs of corresponding elements of second and third arguments (lists). tail fibs
returns tail of the list fibs
(i.e., all elements except for the first one). Thus first element of the list returned by zipWith
is a sum of first and second elements of list fibs
and becomes its third element.
module Main where
import Text.Printf
fibs :: [Int]
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
line n = printf "%d, " $ fibs !! n
main = do
sequence_ $ map line [1..16]
putStrLn "..."
Comments
]]>blog comments powered by Disqus
]]>