module Q_ (Q_(..)) where import Base import Z (Z) import qualified Z (zero, one) import GHC.Real data Q_ = Frac Z Z one = Frac Z.one Z.one instance Show Q_ where show a = "Q[" ++ (show . toRational $ a) ++ "]" instance Eq Q_ where (Frac a b) == (Frac c d) | all (== Z.zero) [a,c] = True (Frac a b) == (Frac c d) | otherwise = (a*d) == (c*b) instance Num Q_ where (Frac a b) + (Frac c d) = Frac (a*d + c*b) (b*d) (Frac a b) - (Frac c d) = Frac (a*d - c*b) (b*d) (Frac a b) * (Frac c d) = Frac (a*c) (b*d) abs (Frac a b) = Frac (abs a) (abs b) negate (Frac a b) = Frac (-a) (b) signum (Frac a b) = Frac (signum $ a*b) Z.one fromInteger n = Frac (fromInteger n) Z.one instance Real Q_ where toRational (Frac a b) = (toInteger a) % (toInteger b) instance Fractional Q_ where (Frac a b) / (Frac c d) = Frac (a*d) (b*c) fromRational (a :% b) = Frac (fromInteger a) (fromInteger b) instance Ord Q_ where (Frac a b) <= (Frac c d) = s (a*d <= c*b) where s k | b*d >= Z.zero = k s k | otherwise = not k
Download