-- The data type of rational numbers module Rat (Rat, rat, numerator, denominator, addR, mulR) where -- A rational number consists of a numerator and a denominator: data Rat = Rat Int Int deriving Eq -- A nice Show instance instance Show Rat where show (Rat n d) = show n ++ "/" ++ show d -- A constructor for rational numbers: rat :: Int -> Int -> Rat rat n d = let g = gcd n d in posDenomRat (div n g) (div d g) where posDenomRat x y = if y<0 then Rat (0 - x) (abs y) else Rat x y -- Selector operations for rational numbers: numerator :: Rat -> Int numerator (Rat n _) = n denominator :: Rat -> Int denominator (Rat _ d) = d -- Operations on rational numbers: addR :: Rat -> Rat -> Rat addR (Rat n1 d1) (Rat n2 d2) = rat (n1*d2 + n2*d1) (d1*d2) mulR :: Rat -> Rat -> Rat mulR (Rat n1 d1) (Rat n2 d2) = rat (n1*n2) (d1*d2)