Showing posts with label functional programming. Show all posts
Showing posts with label functional programming. Show all posts

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

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 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