Haskell Program to print factorial of a number
Program
module Main where
import Text.Printf
factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n - 1)
line x = printf "%d! = %d\n" x $ factorial x
main = mapM_ line [0..8]
Haskell Program to Print Factorial of a Number
This Haskell program computes and prints the factorial of numbers from 0 to 8 using recursion.
1. module Main where
- Defines the
Main
module, which is required for a standalone Haskell program.
2. import Text.Printf
- Imports the
printf
function fromText.Printf
for formatted output.
3. factorial :: Integer -> Integer
- Declares
factorial
as a function that takes anInteger
and returns anInteger
.
4. factorial 0 = 1
- The base case of the recursive function:
0! = 1
.
5. factorial n = n * factorial (n - 1)
- The recursive case: calculates
n!
asn * (n-1)!
.
6. line x = printf "%d! = %d\n" x $ factorial x
- Defines a function
line
that:- Computes
factorial x
. - Formats and prints
x! = factorial(x)
.
- Computes
7. main = mapM_ line [0..8]
- Calls
line
for numbers from0
to8
usingmapM_
, which ensures all print statements execute sequentially.
Key Takeaways
- Uses recursion to compute the factorial.
- Uses pattern matching to define the base case
factorial 0 = 1
. - Uses formatted printing via
printf
. - Uses
mapM_
to iterate over a list and print factorials.
Output
$ ghc factorial.hs
[1 of 1] Compiling Main ( factorial.hs, factorial.o )
Linking factorial ...
$ ./factorial
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320