Haskell Program to print Fibonacci series
Program
module Main where
import Text.Printf
fibs :: [Int]
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
line n = printf "%d\t" $ fibs !! n
main = do
sequence_ $ map line [0..8]
putStrLn ""
Haskell Program to Print Fibonacci Series
This Haskell program generates and prints the Fibonacci series using lazy evaluation and functional programming techniques.
1. module Main where
- Defines the
Mainmodule, which is required for a standalone Haskell program.
2. import Text.Printf
- Imports the
printffunction from theText.Printfmodule to format the output.
3. fibs :: [Int]
- Declares
fibsas an infinite list of integers representing the Fibonacci sequence.
4. fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
- This defines an infinite list of Fibonacci numbers using recursion:
- The list starts with
0and1. - The rest of the sequence is computed using
zipWith (+) fibs (tail fibs), which adds each element to the next one.
- The list starts with
5. line n = printf "%d\t" $ fibs !! n
- Defines a function
linethat prints thenth Fibonacci number usingprintf. fibs !! nretrieves thenth element of thefibslist.
6. main = do
- The
mainfunction executes the program.
7. sequence_ $ map line [0..8]
- Maps the
linefunction over the list[0..8], printing the first 9 Fibonacci numbers. sequence_ensures all actions in the list are executed sequentially.
8. putStrLn ""
- Prints a newline for better formatting.
Key Takeaways
- The Fibonacci sequence is generated efficiently using lazy evaluation.
- The
zipWithfunction is used to compute the next Fibonacci number. - The
printffunction formats the output. - The
sequence_function executes multiple IO actions sequentially.
Output
$ ghc fibonacci.hs
[1 of 1] Compiling Main ( fibonacci.hs, fibonacci.o )
Linking fibonacci ...
$ ./fibonacci
0 1 1 2 3 5 8 13 21