x^y. Reply

S.D.Mechveliani mechvel@math.botik.ru
Wed, 19 Dec 2001 11:12:34 +0300


Toralf Wittner <wittner@uni-duesseldorf.de> writes

> [..]
> power x y
> [..]
>	| y > 0		= x * power x (y-1)
>	| y < 0		= 1 / fromInteger x * power x (y+1)
>
> One recognizes that the function returns either an integer value 
> if y > 0 or a float value if y < 0. Therefore I can't write a 
> signature like 
> pow :: Integer -> Integer -> Integer nor can I do 
> pow :: Integer -> Integer -> Double. 
>
> [..]
> How then would I write this function in Haskell (concerning types)?


The type  Rational  fits the case n < 0 too, and it includes Integer.

But if you still need  Integer | Double,  you can, for example,
introduce a new type of a disjoint union of the above two, and then,
to compute like this:
                      pow (Intg 2) 2     -->  Intg 4  
                      pow (Intg 2) (-2)  -->  D 0.25
                      pow (D 2.0)  (-2)  -->  D 0.25
This is achieved by

  data PowerDom = Intg Integer | D Double  deriving(Eq,Show)

  pow :: PowerDom -> Integer -> PowerDom
  pow x n = p x n
    where
    p (Intg m) n = if  n > 0  then  Intg $ powerInteger m n
                   else  D $ powerDouble (fromInteger m :: Double) n
    p(D d)     n = D $ powerDouble d n

    powerInteger m n = m^n  :: Integer

    powerDouble :: Double -> Integer -> Double
    powerDouble    d         n       =  ... usual way for float

- something like this.


-----------------
Serge Mechveliani
mechvel@botik.ru