[Haskell-beginners] Implementing instance of '^' operator

pmcilroy at gmail.com pmcilroy at gmail.com
Sun Jan 3 06:55:41 UTC 2016


As a ‘hello world’ example for type definitions, I like to define a numeric type that can handle the mod p multiplicative group, where p is prime. This requires:
• Implementing interface functions
• Defining non-trivial implementations, where constructor must be private, etc.
• Invoking an abstract superclass concrete instance method from within the subclass method definition
The latter appears not to be possible in Haskell. Is this true?
Here’s the basic code, but I punted on x^n. It looks like I’d have to paste in the entire original definition of ‘^’.
data Modp a = Modp a a deriving (Eq, Show)

mkModp p n | isPrime p = Modp p (n `mod` p)
           | otherwise = error $ show p ++ " is not a prime"

instance Integral a => Num (Modp a) where
         (Modp q n) + (Modp p m) | p==q = Modp p $ (n+m) `mod` p
                                 | otherwise = error $ "unequal moduli"
         (Modp p n) * (Modp q m) | p==q = Modp p $ (n*m) `mod` p
                                 | otherwise = error $ "unequal moduli"
         negate (Modp p n) = Modp p (p-n)
         -- can't reuse base because ^ is impl. directly in prelude
{-       (Modp p x) ^ n | n <= p  = (Modp p x) `baseExp` n
                        | n1 == 0 = (Modp p x)
                        | n > p   =  x ^ n1
             where baseExp = ^ in Num
                   n1      = n `mod` p
-}
instance Integral a => Fractional (Modp a) where
         recip (Modp p n) = (Modp p n)^(p-2)


isPrime p = True	-- stub
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20160102/dd8c3229/attachment.html>


More information about the Beginners mailing list