Saturday, 4 June 2016

Haskell: Implement a function that gives powers of 2


Sample.hs
power :: Integer -> Integer -> Integer
power m n
    | (n == 0) = 1
    | (n < 0 ) = error "Cannot raise an integer m to a negative power -n."
    | otherwise = m * power m (n-1)

twoPower = power 2

*Main> :load Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> twoPower 5
32
*Main> twoPower (-5)
*** Exception: Cannot raise an integer m to a negative power -n.
*Main> 
*Main> twoPower 0
1



Previous                                                 Next                                                 Home

No comments:

Post a Comment