Gaussian integers. Reply

S.D.Mechveliani mechvel@math.botik.ru
Tue, 19 Mar 2002 15:05:03 +0300


dominic.j.steinitz@britishairways.com  writes

> On holiday, I started reading about Gaussian integers (as you do) and I
> thought this should be a piece of cake for Haskell. I get the following
> error in Hugs:
> [..]
> 
> data Integral a => Gaussian a = Gaussian a a
>   deriving (Eq, Show)
>
> instance Num (Gaussian a) where
>   Gaussian a b - Gaussian a' b' = Gaussian (a-a') (b-b')
>   Gaussian a b + Gaussian a' b' = Gaussian (a+a') (b+b')
>   Gaussian a b * Gaussian a' b' = Gaussian (a*a' - b*b') (a*b' + b*a')
>   negate (Gaussian a b) = Gaussian (negate a) (negate b)
>   fromInteger a = Gaussian (fromIntegral a) 0


To my mind, it is not good to set  `Integral a =>'  to data declaration.
It is better to set such things in the  instance  declarations.
Try, say

  data Gaussian a = Gau a a deriving (Eq, Show)

  instance Integral a => Num (Gaussian a)
    where
    Gau a b - Gau a' b' = Gau (a-a') (b-b')
    ...

  ------------------------------------------------- 
  scico:~/t> ghci M.hs
  ...                  GHC Interactive, version 5.02.2, for Haskell 98.
  ...
  M> Gau 1 1 * Gau 1 (-1)
  Gau 2 0


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