2 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
3 {-# OPTIONS_HADDOCK hide #-}
4 -----------------------------------------------------------------------------
7 -- Copyright : (c) The University of Glasgow, 1994-2002
8 -- License : see libraries/base/LICENSE
10 -- Maintainer : cvs-ghc@haskell.org
11 -- Stability : internal
12 -- Portability : non-portable (GHC Extensions)
14 -- The types 'Ratio' and 'Rational', and the classes 'Real', 'Fractional',
15 -- 'Integral', and 'RealFrac'.
17 -----------------------------------------------------------------------------
30 infixl 7 /, `quot`, `rem`, `div`, `mod`
33 default () -- Double isn't available yet,
34 -- and we shouldn't be using defaults anyway
38 %*********************************************************
40 \subsection{The @Ratio@ and @Rational@ types}
42 %*********************************************************
45 -- | Rational numbers, with numerator and denominator of some 'Integral' type.
46 data (Integral a) => Ratio a = !a :% !a deriving (Eq)
48 -- | Arbitrary-precision rational numbers, represented as a ratio of
49 -- two 'Integer' values. A rational number may be constructed using
51 type Rational = Ratio Integer
53 ratioPrec, ratioPrec1 :: Int
54 ratioPrec = 7 -- Precedence of ':%' constructor
55 ratioPrec1 = ratioPrec + 1
57 infinity, notANumber, negativeZero :: Rational
60 negativeZero = 0 :% (-1)
62 -- Use :%, not % for Inf/NaN; the latter would
63 -- immediately lead to a runtime error, because it normalises.
68 -- | Forms the ratio of two integral numbers.
69 {-# SPECIALISE (%) :: Integer -> Integer -> Rational #-}
70 (%) :: (Integral a) => a -> a -> Ratio a
72 -- | Extract the numerator of the ratio in reduced form:
73 -- the numerator and denominator have no common factor and the denominator
75 numerator :: (Integral a) => Ratio a -> a
77 -- | Extract the denominator of the ratio in reduced form:
78 -- the numerator and denominator have no common factor and the denominator
80 denominator :: (Integral a) => Ratio a -> a
83 \tr{reduce} is a subsidiary function used only in this module .
84 It normalises a ratio by dividing both numerator and denominator by
85 their greatest common divisor.
88 reduce :: (Integral a) => a -> a -> Ratio a
89 {-# SPECIALISE reduce :: Integer -> Integer -> Rational #-}
90 reduce _ 0 = error "Ratio.%: zero denominator"
91 reduce x y = (x `quot` d) :% (y `quot` d)
96 x % y = reduce (x * signum y) (abs y)
98 numerator (x :% _) = x
99 denominator (_ :% y) = y
103 %*********************************************************
105 \subsection{Standard numeric classes}
107 %*********************************************************
110 class (Num a, Ord a) => Real a where
111 -- | the rational equivalent of its real argument with full precision
112 toRational :: a -> Rational
114 -- | Integral numbers, supporting integer division.
116 -- Minimal complete definition: 'quotRem' and 'toInteger'
117 class (Real a, Enum a) => Integral a where
118 -- | integer division truncated toward zero
120 -- | integer remainder, satisfying
122 -- > (x `quot` y)*y + (x `rem` y) == x
124 -- | integer division truncated toward negative infinity
126 -- | integer modulus, satisfying
128 -- > (x `div` y)*y + (x `mod` y) == x
130 -- | simultaneous 'quot' and 'rem'
131 quotRem :: a -> a -> (a,a)
132 -- | simultaneous 'div' and 'mod'
133 divMod :: a -> a -> (a,a)
134 -- | conversion to 'Integer'
135 toInteger :: a -> Integer
141 n `quot` d = q where (q,_) = quotRem n d
142 n `rem` d = r where (_,r) = quotRem n d
143 n `div` d = q where (q,_) = divMod n d
144 n `mod` d = r where (_,r) = divMod n d
146 divMod n d = if signum r == negate (signum d) then (q-1, r+d) else qr
147 where qr@(q,r) = quotRem n d
149 -- | Fractional numbers, supporting real division.
151 -- Minimal complete definition: 'fromRational' and ('recip' or @('/')@)
152 class (Num a) => Fractional a where
153 -- | fractional division
155 -- | reciprocal fraction
157 -- | Conversion from a 'Rational' (that is @'Ratio' 'Integer'@).
158 -- A floating literal stands for an application of 'fromRational'
159 -- to a value of type 'Rational', so such literals have type
160 -- @('Fractional' a) => a@.
161 fromRational :: Rational -> a
168 -- | Extracting components of fractions.
170 -- Minimal complete definition: 'properFraction'
171 class (Real a, Fractional a) => RealFrac a where
172 -- | The function 'properFraction' takes a real fractional number @x@
173 -- and returns a pair @(n,f)@ such that @x = n+f@, and:
175 -- * @n@ is an integral number with the same sign as @x@; and
177 -- * @f@ is a fraction with the same type and sign as @x@,
178 -- and with absolute value less than @1@.
180 -- The default definitions of the 'ceiling', 'floor', 'truncate'
181 -- and 'round' functions are in terms of 'properFraction'.
182 properFraction :: (Integral b) => a -> (b,a)
183 -- | @'truncate' x@ returns the integer nearest @x@ between zero and @x@
184 truncate :: (Integral b) => a -> b
185 -- | @'round' x@ returns the nearest integer to @x@;
186 -- the even integer if @x@ is equidistant between two integers
187 round :: (Integral b) => a -> b
188 -- | @'ceiling' x@ returns the least integer not less than @x@
189 ceiling :: (Integral b) => a -> b
190 -- | @'floor' x@ returns the greatest integer not greater than @x@
191 floor :: (Integral b) => a -> b
193 {-# INLINE truncate #-}
194 truncate x = m where (m,_) = properFraction x
196 round x = let (n,r) = properFraction x
197 m = if r < 0 then n - 1 else n + 1
198 in case signum (abs r - 0.5) of
200 0 -> if even n then n else m
202 _ -> error "round default defn: Bad value"
204 ceiling x = if r > 0 then n + 1 else n
205 where (n,r) = properFraction x
207 floor x = if r < 0 then n - 1 else n
208 where (n,r) = properFraction x
212 These 'numeric' enumerations come straight from the Report
215 numericEnumFrom :: (Fractional a) => a -> [a]
216 numericEnumFrom n = n `seq` (n : numericEnumFrom (n + 1))
218 numericEnumFromThen :: (Fractional a) => a -> a -> [a]
219 numericEnumFromThen n m = n `seq` m `seq` (n : numericEnumFromThen m (m+m-n))
221 numericEnumFromTo :: (Ord a, Fractional a) => a -> a -> [a]
222 numericEnumFromTo n m = takeWhile (<= m + 1/2) (numericEnumFrom n)
224 numericEnumFromThenTo :: (Ord a, Fractional a) => a -> a -> a -> [a]
225 numericEnumFromThenTo e1 e2 e3
226 = takeWhile predicate (numericEnumFromThen e1 e2)
229 predicate | e2 >= e1 = (<= e3 + mid)
230 | otherwise = (>= e3 + mid)
234 %*********************************************************
236 \subsection{Instances for @Int@}
238 %*********************************************************
241 instance Real Int where
242 toRational x = toInteger x % 1
244 instance Integral Int where
245 toInteger (I# i) = smallInteger i
248 | b == 0 = divZeroError
249 | a == minBound && b == (-1) = overflowError
250 | otherwise = a `quotInt` b
253 | b == 0 = divZeroError
254 | a == minBound && b == (-1) = overflowError
255 | otherwise = a `remInt` b
258 | b == 0 = divZeroError
259 | a == minBound && b == (-1) = overflowError
260 | otherwise = a `divInt` b
263 | b == 0 = divZeroError
264 | a == minBound && b == (-1) = overflowError
265 | otherwise = a `modInt` b
268 | b == 0 = divZeroError
269 | a == minBound && b == (-1) = overflowError
270 | otherwise = a `quotRemInt` b
273 | b == 0 = divZeroError
274 | a == minBound && b == (-1) = overflowError
275 | otherwise = a `divModInt` b
279 %*********************************************************
281 \subsection{Instances for @Integer@}
283 %*********************************************************
286 instance Real Integer where
289 instance Integral Integer where
292 _ `quot` 0 = divZeroError
293 n `quot` d = n `quotInteger` d
295 _ `rem` 0 = divZeroError
296 n `rem` d = n `remInteger` d
298 _ `divMod` 0 = divZeroError
299 a `divMod` b = case a `divModInteger` b of
302 _ `quotRem` 0 = divZeroError
303 a `quotRem` b = case a `quotRemInteger` b of
306 -- use the defaults for div & mod
310 %*********************************************************
312 \subsection{Instances for @Ratio@}
314 %*********************************************************
317 instance (Integral a) => Ord (Ratio a) where
318 {-# SPECIALIZE instance Ord Rational #-}
319 (x:%y) <= (x':%y') = x * y' <= x' * y
320 (x:%y) < (x':%y') = x * y' < x' * y
322 instance (Integral a) => Num (Ratio a) where
323 {-# SPECIALIZE instance Num Rational #-}
324 (x:%y) + (x':%y') = reduce (x*y' + x'*y) (y*y')
325 (x:%y) - (x':%y') = reduce (x*y' - x'*y) (y*y')
326 (x:%y) * (x':%y') = reduce (x * x') (y * y')
327 negate (x:%y) = (-x) :% y
328 abs (x:%y) = abs x :% y
329 signum (x:%_) = signum x :% 1
330 fromInteger x = fromInteger x :% 1
332 instance (Integral a) => Fractional (Ratio a) where
333 {-# SPECIALIZE instance Fractional Rational #-}
334 (x:%y) / (x':%y') = (x*y') % (y*x')
336 fromRational (x:%y) = fromInteger x :% fromInteger y
338 instance (Integral a) => Real (Ratio a) where
339 {-# SPECIALIZE instance Real Rational #-}
340 toRational (x:%y) = toInteger x :% toInteger y
342 instance (Integral a) => RealFrac (Ratio a) where
343 {-# SPECIALIZE instance RealFrac Rational #-}
344 properFraction (x:%y) = (fromInteger (toInteger q), r:%y)
345 where (q,r) = quotRem x y
347 instance (Integral a) => Show (Ratio a) where
348 {-# SPECIALIZE instance Show Rational #-}
349 showsPrec p (x:%y) = showParen (p > ratioPrec) $
350 showsPrec ratioPrec1 x .
352 -- H98 report has spaces round the %
353 -- but we removed them [May 04]
354 -- and added them again for consistency with
355 -- Haskell 98 [Sep 08, #1920]
356 showsPrec ratioPrec1 y
358 instance (Integral a) => Enum (Ratio a) where
359 {-# SPECIALIZE instance Enum Rational #-}
363 toEnum n = fromIntegral n :% 1
364 fromEnum = fromInteger . truncate
366 enumFrom = numericEnumFrom
367 enumFromThen = numericEnumFromThen
368 enumFromTo = numericEnumFromTo
369 enumFromThenTo = numericEnumFromThenTo
373 %*********************************************************
375 \subsection{Coercions}
377 %*********************************************************
380 -- | general coercion from integral types
381 fromIntegral :: (Integral a, Num b) => a -> b
382 fromIntegral = fromInteger . toInteger
385 "fromIntegral/Int->Int" fromIntegral = id :: Int -> Int
388 -- | general coercion to fractional types
389 realToFrac :: (Real a, Fractional b) => a -> b
390 realToFrac = fromRational . toRational
393 "realToFrac/Int->Int" realToFrac = id :: Int -> Int
397 %*********************************************************
399 \subsection{Overloaded numeric functions}
401 %*********************************************************
404 -- | Converts a possibly-negative 'Real' value to a string.
405 showSigned :: (Real a)
406 => (a -> ShowS) -- ^ a function that can show unsigned values
407 -> Int -- ^ the precedence of the enclosing context
408 -> a -- ^ the value to show
410 showSigned showPos p x
411 | x < 0 = showParen (p > 6) (showChar '-' . showPos (-x))
412 | otherwise = showPos x
414 even, odd :: (Integral a) => a -> Bool
415 even n = n `rem` 2 == 0
418 -------------------------------------------------------
419 -- | raise a number to a non-negative integral power
420 {-# SPECIALISE (^) ::
421 Integer -> Integer -> Integer,
422 Integer -> Int -> Integer,
423 Int -> Int -> Int #-}
424 (^) :: (Num a, Integral b) => a -> b -> a
425 x0 ^ y0 | y0 < 0 = error "Negative exponent"
427 | otherwise = f x0 y0
428 where -- f : x0 ^ y0 = x ^ y
429 f x y | even y = f (x * x) (y `quot` 2)
431 | otherwise = g (x * x) ((y - 1) `quot` 2) x
432 -- g : x0 ^ y0 = (x ^ y) * z
433 g x y z | even y = g (x * x) (y `quot` 2) z
435 | otherwise = g (x * x) ((y - 1) `quot` 2) (x * z)
437 -- | raise a number to an integral power
438 {-# SPECIALISE (^^) ::
439 Rational -> Int -> Rational #-}
440 (^^) :: (Fractional a, Integral b) => a -> b -> a
441 x ^^ n = if n >= 0 then x^n else recip (x^(negate n))
444 -------------------------------------------------------
445 -- | @'gcd' x y@ is the greatest (positive) integer that divides both @x@
446 -- and @y@; for example @'gcd' (-3) 6@ = @3@, @'gcd' (-3) (-6)@ = @3@,
447 -- @'gcd' 0 4@ = @4@. @'gcd' 0 0@ raises a runtime error.
448 gcd :: (Integral a) => a -> a -> a
449 gcd 0 0 = error "Prelude.gcd: gcd 0 0 is undefined"
450 gcd x y = gcd' (abs x) (abs y)
452 gcd' a b = gcd' b (a `rem` b)
454 -- | @'lcm' x y@ is the smallest positive integer that both @x@ and @y@ divide.
455 lcm :: (Integral a) => a -> a -> a
456 {-# SPECIALISE lcm :: Int -> Int -> Int #-}
459 lcm x y = abs ((x `quot` (gcd x y)) * y)
461 #ifdef OPTIMISE_INTEGER_GCD_LCM
463 "gcd/Int->Int->Int" gcd = gcdInt
464 "gcd/Integer->Integer->Integer" gcd = gcdInteger'
465 "lcm/Integer->Integer->Integer" lcm = lcmInteger
468 gcdInteger' :: Integer -> Integer -> Integer
469 gcdInteger' 0 0 = error "GHC.Real.gcdInteger': gcd 0 0 is undefined"
470 gcdInteger' a b = gcdInteger a b
472 gcdInt :: Int -> Int -> Int
473 gcdInt 0 0 = error "GHC.Real.gcdInt: gcd 0 0 is undefined"
474 gcdInt a b = fromIntegral (gcdInteger (fromIntegral a) (fromIntegral b))
477 integralEnumFrom :: (Integral a, Bounded a) => a -> [a]
478 integralEnumFrom n = map fromInteger [toInteger n .. toInteger (maxBound `asTypeOf` n)]
480 integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a]
481 integralEnumFromThen n1 n2
482 | i_n2 >= i_n1 = map fromInteger [i_n1, i_n2 .. toInteger (maxBound `asTypeOf` n1)]
483 | otherwise = map fromInteger [i_n1, i_n2 .. toInteger (minBound `asTypeOf` n1)]
488 integralEnumFromTo :: Integral a => a -> a -> [a]
489 integralEnumFromTo n m = map fromInteger [toInteger n .. toInteger m]
491 integralEnumFromThenTo :: Integral a => a -> a -> a -> [a]
492 integralEnumFromThenTo n1 n2 m
493 = map fromInteger [toInteger n1, toInteger n2 .. toInteger m]