{-# OPTIONS_GHC -fglasgow-exts #-} module Q where import EqClass import GHC.Real data Q z = Q (z,z) type Q' z = EqClass (Q z) instance (Real z, Integral z) => Show (Q z) where show z = "Q[" ++ show (toRational z) ++ "]" instance (Num z, Eq z) => Eq (Q z) where (Q (a,b)) == (Q (c,d)) = a * d == c * b instance (Num z, Integral z) => Num (Q z) where (Q (a,b)) + (Q (c,d)) = Q (a*d + c*b, b*d) (Q (a,b)) - (Q (c,d)) = Q (a*d - c*b, b*d) (Q (a,b)) * (Q (c,d)) = Q (a*c, b*d) signum (Q (a,b)) = fromInteger . toInteger $ signum (a*b) abs x = x * signum x fromInteger n = Q (fromInteger n, 1) instance (Num z, Integral z) => Fractional (Q z) where (Q (a,b)) / (Q (c,d)) = Q (a*d, b*c) fromRational (a :% b) = Q (fromInteger a, fromInteger b) instance (Num z, Ord z) => Ord (Q z) where (Q (a,b)) <= (Q (c,d)) | b * d > 0 = a * d <= c * b (Q (a,b)) <= (Q (c,d)) | b * d < 0 = a * d > c * b instance (Real z, Integral z) => Real (Q z) where toRational (Q (a,b)) = toRational a / toRational b
Download