1   module Rationals 
    2 
    3                 (Rationals(..),rndNR)
    4 
    5   where
    6 
    7   import Ratio--1.3
    8   infix 7 :%%
    9 
   10 
   11 
   12 
   13 
   14   data Rationals = Int :%% Int deriving (Show{-was:Text-},Eq)
   15 
   16 
   17 
   18 
   19 
   20   instance Ord Rationals where
   21         (p :%% q) <= (r :%% s) = p*s <= q*r
   22 
   23   instance Num Rationals where
   24 
   25 
   26 
   27 
   28 
   29 
   30 
   31 
   32         (+) (p :%% 1) (r :%% 1) = (p+r) :%% 1
   33         (+) (p :%% 1) (r :%% s) = simplify (p*s +r) s
   34         (+) (p :%% q) (r :%% 1) = simplify (p+ q*r) q
   35         (+) (p :%% q) (r :%% s) = simplify (p*s+q*r) (q*s)
   36 
   37 
   38 
   39 
   40 
   41 
   42         (*) (p :%% 1) (r :%% 1) = (p*r) :%% 1
   43         (*) (p :%% 1) (r :%% s) = simplify (p*r) s
   44         (*) (p :%% q) (r :%% 1) = simplify (p*r) q
   45         (*) (p :%% q) (r :%% s) = simplify (p*r) (q*s)
   46 
   47 
   48 
   49 
   50         negate (x :%% y) = (negate x :%% y)
   51 
   52 
   53 
   54 
   55         abs (x :%% y) = (abs x :%% y)
   56 
   57 
   58 
   59         signum (x :%% _) = (signum x:%%1)
   60 
   61 
   62 
   63         fromInteger x = (fromInteger x) :%% 1
   64 
   65 
   66 
   67   instance Fractional Rationals where
   68 
   69 
   70 
   71 
   72 
   73         (/) x y@(r :%% s)       | r==0 = error "Attempt to divide by Zero" 
   74                                 | otherwise = x * (s :%% r) 
   75 
   76 
   77 
   78 
   79 
   80 
   81         fromRational r = (fromInteger (numerator r)) :%% (fromInteger (denominator r))
   82 
   83 
   84 
   85 
   86 
   87 
   88 
   89   simplify :: Int -> Int -> Rationals
   90   simplify x y  = (signum bottom*top) :%% abs bottom
   91                         where 
   92                         top = x `div` d
   93                         bottom = y `div` d
   94                         d = gcd x y
   95 
   96 
   97 
   98 
   99   instance Real Rationals where
  100         toRational (x:%%y) = toInteger x % toInteger y
  101 
  102   instance Enum Rationals where -- partain
  103      enumFrom           = error "Enum.Rationals.enumFrom"
  104      enumFromThen       = error "Enum.Rationals.enumFromThen"
  105      enumFromTo         = error "Enum.Rationals.enumFromTo"
  106      enumFromThenTo     = error "Enum.Rationals.enumFromThenTo"
  107 
  108 
  109 
  110 
  111   top ::  Rationals -> Int
  112   top (a :%% b) = a
  113 
  114 
  115 
  116 
  117   bottom :: Rationals -> Int
  118   bottom (a :%% b) = b
  119 
  120 
  121 
  122 
  123 
  124 
  125 
  126 
  127   rndNR ::  Rationals -> Int
  128   rndNR (a :%% 1) = fromInteger (toInteger a)
  129   rndNR a =  fromInteger (toInteger (div n d))
  130                           where r = (1/2) + a
  131                                 n = top r
  132                                 d = bottom r
  133 
  134