praxis

Various programming exercises.
git clone git://git.jtobin.io/praxis.git
Log | Files | Refs

Power.hs (542B)


      1 
      2 module Power where
      3 
      4 import Data.Foldable
      5 import Data.Monoid
      6 
      7 powLinear :: Num c => Product c -> Int -> c
      8 powLinear a b = getProduct . fold $ replicate b a
      9 
     10 powLogarithmic :: (Num b, Integral a) => b -> a -> b
     11 powLogarithmic a b
     12   | b <  0 = error "nonnegative powers only"
     13   | b == 0 = 1
     14   | even b =
     15       let term = powLogarithmic a (b `quot` 2)
     16       in  term * term
     17   | otherwise =
     18       let term = powLogarithmic a (pred b `quot` 2)
     19       in  a * term * term
     20 
     21 powConstant :: Floating a => a -> a -> a
     22 powConstant a b = exp (log a * b)
     23