diff --git a/lib/Data/Ratio.hs b/lib/Data/Ratio.hs index 0d83798a..171da8ee 100644 --- a/lib/Data/Ratio.hs +++ b/lib/Data/Ratio.hs @@ -17,6 +17,7 @@ import Data.Num import Data.Ord import Data.Ratio_Type import Data.Real +import Data.RealFrac import Text.Show {- in Data.Ratio_Type @@ -98,3 +99,16 @@ numerator (x :% _) = x denominator :: forall a . Ratio a -> a denominator (_ :% y) = y + +instance (Ord a, Integral a) => RealFrac (Ratio a) where + properFraction (x:%y) = (fromInteger (toInteger q), r:%y) + where (q, r) = quotRem x y + round r = + let + (n, f) = properFraction r + x = if r < 0 then -1 else 1 + in case (compare (abs f) 0.5, odd n) of + (LT, _) -> n + (EQ, False) -> n + (EQ, True) -> n + x + (GT, _) -> n + x