src/Pure/General/rat.ML
changeset 63210 a0685d2b420b
parent 63209 82cd1d481eb9
child 63211 0bec0d1d9998
equal deleted inserted replaced
63209:82cd1d481eb9 63210:a0685d2b420b
     6 *)
     6 *)
     7 
     7 
     8 signature RAT =
     8 signature RAT =
     9 sig
     9 sig
    10   eqtype rat
    10   eqtype rat
    11   exception DIVZERO
       
    12   val of_int: int -> rat
    11   val of_int: int -> rat
    13   val make: int * int -> rat
    12   val make: int * int -> rat
    14   val dest: rat -> int * int
    13   val dest: rat -> int * int
    15   val string_of_rat: rat -> string
    14   val string_of_rat: rat -> string
    16   val signed_string_of_rat: rat -> string
    15   val signed_string_of_rat: rat -> string
    35 
    34 
    36 fun common (p1, q1) (p2, q2) =
    35 fun common (p1, q1) (p2, q2) =
    37   let val m = PolyML.IntInf.lcm (q1, q2)
    36   let val m = PolyML.IntInf.lcm (q1, q2)
    38   in ((p1 * (m div q1), p2 * (m div q2)), m) end;
    37   in ((p1 * (m div q1), p2 * (m div q2)), m) end;
    39 
    38 
    40 exception DIVZERO;
    39 fun make (p, 0) = raise Div
    41 
    40   | make (p, q) =
    42 fun make (p, q) =
    41     let
    43   let
    42       val m = PolyML.IntInf.gcd (p, q);
    44     val m = PolyML.IntInf.gcd (p, q);
    43       val (p', q') = (p div m, q div m);
    45     val (p', q') = (p div m, q div m) handle Div => raise DIVZERO;
    44     in Rat (if q' < 0 then (~ p', ~ q') else (p', q')) end
    46   in Rat (if q' < 0 then (~ p', ~ q') else (p', q')) end
       
    47 
    45 
    48 fun dest (Rat r) = r;
    46 fun dest (Rat r) = r;
    49 
    47 
    50 fun of_int i = Rat (i, 1);
    48 fun of_int i = Rat (i, 1);
    51 
    49 
    84 fun neg (Rat (p, q)) = Rat (~ p, q);
    82 fun neg (Rat (p, q)) = Rat (~ p, q);
    85 
    83 
    86 fun inv (Rat (p, q)) =
    84 fun inv (Rat (p, q)) =
    87   (case Integer.sign p of
    85   (case Integer.sign p of
    88     LESS => Rat (~ q, ~ p)
    86     LESS => Rat (~ q, ~ p)
    89   | EQUAL => raise DIVZERO
    87   | EQUAL => raise Div
    90   | GREATER => Rat (q, p));
    88   | GREATER => Rat (q, p));
    91 
    89 
    92 fun floor (Rat (p, q)) = p div q;
    90 fun floor (Rat (p, q)) = p div q;
    93 
    91 
    94 fun ceil (Rat (p, q)) =
    92 fun ceil (Rat (p, q)) =