Saturday, February 28, 2009

Raising a number to the power of another number. exponent. in haskell

power :: Float -> Float -> Float
power m n
| n == 0        = 1
| n > 0         = m* power m (n-1)
| otherwise     = (1 / m)* power m (n+1)

Friday, February 27, 2009

finding the highest common factor/divisor for two integers in haskell

hcf :: Int -> Int -> Int
--handles all cases of zero
hcf 0 0 = undefined 
hcf m 0 = abs m
hcf 0 n = abs n
hcf m n 
    | m == n       = m 
    | m > n        = hcf n (rem m n) 
    | otherwise    = hcf n m

fibonacci sequence in haskell : not very efficient

fib :: Int -> Int
fib n
| n == 0        = 0
| n == 1        = 1
| n > 1         = fib (n - 2) + fib (n - 1)

Integer square root of a positive integer in haskell

squareRoot :: Int -> Int
squareRoot n 
| n ==  1              = 1 
| otherwise            = div (k + ( div n k)) 2
where k = squareRoot(n-1) 

Using recursive addition to multiply in haskell

multiply :: Int -> Int -> Int
multiply m n
| n >= 1        = m + multiply (n-1) m
| otherwise     = 0

Finding the factorial in haskell.

rangeProduct :: Float -> Float -> Float
rangeProduct m n
| m>n             = 0
| m==n            = m
| otherwise       = m * rangeProduct (m+1) n

--4.6 Factorial

factorial :: Float -> Float
factorial n
| n == 0          = 1
| otherwise       = rangeProduct 1 n

finding out how many are equal amongst three numnbers in haskell

howManyEqual :: Int -> Int -> Int -> Int
howManyEqual x y z 
|((equal x y) + (equal y z) + (equal x z)) == 1     = 2
| otherwise                                         = (equal x y) + (equal y z) + (equal x z)
equal :: Int -> Int -> Int
equal x y 
| x == y           = 1
| otherwise        = 0

Finding max of two, three or four in haskell

maxTwo :: Int -> Int -> Int
maxTwo x y
| x>y                   = x
| otherwise             = y
maxThree :: Int -> Int -> Int -> Int
maxThree x y z 
|maxTwo x y > z            = maxTwo x y
|otherwise   = z

maxFour :: Int -> Int -> Int -> Int -> Int
maxFour v x y z
| maxThree v x y > z      = maxThree v x y
| otherwise               = z

Finding the number of roots in a quadratic equation in haskell

rootFunction :: Float -> Float -> Float -> Int
rootFunction a b c
| a == 0        = dRoots a b c
| otherwise     = numberNDroots a b c

numberNDroots :: Float -> Float -> Float -> Int
numberNDroots a b c 
| b^2 > (4.0*a*c)      = 2
| b^2 == (4.0*a*c)     = 1
| b^2 < (4.0*a*c)      = 0
dRoots :: Float -> Float -> Float -> Int
dRoots a b c 
| b /= 0               = 1
| b == 0 && c /= 0     = 0
| b == 0 && c == 0     = 3

Finding the average of three numbers in haskell

averageThree :: Float -> Float -> Float -> Float
averageThree  a b c = (a + (b + c))/3.0

isAbove :: Float -> Float -> Int
isAbove a avg
 | a > avg = 1
 | otherwise = 0

numAbove :: Float -> Float -> Float -> Int
numAbove a b c = (isAbove a avg) + (isAbove b avg) + (isAbove c avg)
  where
   avg = averageThree a b c