Factorial in Haskell
Example for versions GHC 6.10.4
This example uses recursive factorial definition and consists of three major parts:
factorialfunction, which takes one argument of
Integertype (integer number of unlimited precision) and returns the same type. The function is defined recursively, and types of argument and return are given explicitly to avoid ambiguity.
linefunction, which prints the number and its factorial in required format. Use of
printfcommand is the same as in C++.
printing the numbers and their factorials themselves.
[0..16]creates a list of numbers from 0 to 16, inclusive. Function
mapapplies first argument (
linefunction) to each element of second argument (
[0..16]list) and as a result creates a list of so-called “output actions” (which can be used as values in Haskell). To combine these actions in one we use
sequence_command, which is applied to a list of actions, executes first action from the list and recursively applies it to the tail of the list. But for simplicity, we use
mapM_, which combines
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..16]