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 Main module, which is required for a standalone Haskell program.

2. import Text.Printf

  • Imports the printf function from the Text.Printf module to format the output.

3. fibs :: [Int]

  • Declares fibs as 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 0 and 1.
    • The rest of the sequence is computed using zipWith (+) fibs (tail fibs), which adds each element to the next one.

5. line n = printf "%d\t" $ fibs !! n

  • Defines a function line that prints the nth Fibonacci number using printf.
  • fibs !! n retrieves the nth element of the fibs list.

6. main = do

  • The main function executes the program.

7. sequence_ $ map line [0..8]

  • Maps the line function 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 zipWith function is used to compute the next Fibonacci number.
  • The printf function 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