A Haskell A Day: Factorial Example

By Xah Lee. Date:

Example of a factorial.

fac :: Integer -> Integer
fac 0 = 1
fac n | n > 0 = n * fac (n-1)

Note that this is defined using pattern matching. Note the third line, with “ | n > 0”. That is a conditional for the pattern “n”. This is called “guards” in Haskell.

Here's another way to define it.

fac = product . enumFromTo 1

Here's two examples of defining the boolean function “and”.

and1 :: Bool -> Bool -> Bool
and1 a b = if a == b then a else False

another way

and2 :: Bool -> Bool -> Bool
and2 True True = True
and2 x y = False 

Here's a example of a function that returns the root of a polynomial a*x^2 + b*x + c == 0.

roots :: (Float, Float, Float) -> (Float, Float) 
roots (a,b,c) = (x1, x2) where
  x1 = e + sqrt d / (2 * a)
  x2 = e - sqrt d / (2 * a)
  d = b * b - 4 * a * c 
  e = - b / (2 * a) 

define some list like thing to feed to roots.:

p1, p2 :: (Float, Float, Float)
p1 = (1.0, 2.0, 1.0)
p2 = (1.0, 1.0, 1.0)

Sample definition of a function that counts the number of elements in a list:

length                  :: [a] -> Integer
length []               =  0
length (x:xs)           =  1 + length xs
2005-10