TUTORIALS

Haskell Program to print factorial of a number

Written By: Koushik S
Created at: 28-June-2023 20:36:19
Modified at: 28-June-2023 20:36:39

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]

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
Article Tags:
  • Number
There are no likes. Be the first one to like
Likes: 0
Comments: 0