Factorial in Haskell
Example for versions
GHC 6.10.4
This example uses recursive factorial definition and consists of three major parts:
-
definition of
factorial
function, which takes one argument ofInteger
type (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. -
definition of
line
function, which prints the number and its factorial in required format. Use of
printf
command 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. Functionmap
applies first argument (line
function) 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 usesequence_
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 usemapM_
, which combinesmap
andsequence_
.
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]
Comments
]]>blog comments powered by Disqus
]]>