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 :: Rational
61 -- Use :%, not % for Inf/NaN; the latter would
62 -- immediately lead to a runtime error, because it normalises.
67 -- | Forms the ratio of two integral numbers.
68 {-# SPECIALISE (%) :: Integer -> Integer -> Rational #-}
69 (%) :: (Integral a) => a -> a -> Ratio a
71 -- | Extract the numerator of the ratio in reduced form:
72 -- the numerator and denominator have no common factor and the denominator
74 numerator :: (Integral a) => Ratio a -> a
76 -- | Extract the denominator of the ratio in reduced form:
77 -- the numerator and denominator have no common factor and the denominator
79 denominator :: (Integral a) => Ratio a -> a
82 \tr{reduce} is a subsidiary function used only in this module .
83 It normalises a ratio by dividing both numerator and denominator by
84 their greatest common divisor.
87 reduce :: (Integral a) => a -> a -> Ratio a
88 {-# SPECIALISE reduce :: Integer -> Integer -> Rational #-}
89 reduce _ 0 = error "Ratio.%: zero denominator"
90 reduce x y = (x `quot` d) :% (y `quot` d)
95 x % y = reduce (x * signum y) (abs y)
97 numerator (x :% _) = x
98 denominator (_ :% y) = y
102 %*********************************************************
104 \subsection{Standard numeric classes}
106 %*********************************************************
109 class (Num a, Ord a) => Real a where
110 -- | the rational equivalent of its real argument with full precision
111 toRational :: a -> Rational
113 -- | Integral numbers, supporting integer division.
115 -- Minimal complete definition: 'quotRem' and 'toInteger'
116 class (Real a, Enum a) => Integral a where
117 -- | integer division truncated toward zero
119 -- | integer remainder, satisfying
121 -- > (x `quot` y)*y + (x `rem` y) == x
123 -- | integer division truncated toward negative infinity
125 -- | integer modulus, satisfying
127 -- > (x `div` y)*y + (x `mod` y) == x
129 -- | simultaneous 'quot' and 'rem'
130 quotRem :: a -> a -> (a,a)
131 -- | simultaneous 'div' and 'mod'
132 divMod :: a -> a -> (a,a)
133 -- | conversion to 'Integer'
134 toInteger :: a -> Integer
140 n `quot` d = q where (q,_) = quotRem n d
141 n `rem` d = r where (_,r) = quotRem n d
142 n `div` d = q where (q,_) = divMod n d
143 n `mod` d = r where (_,r) = divMod n d
145 divMod n d = if signum r == negate (signum d) then (q-1, r+d) else qr
146 where qr@(q,r) = quotRem n d
148 -- | Fractional numbers, supporting real division.
150 -- Minimal complete definition: 'fromRational' and ('recip' or @('/')@)
151 class (Num a) => Fractional a where
152 -- | fractional division
154 -- | reciprocal fraction
156 -- | Conversion from a 'Rational' (that is @'Ratio' 'Integer'@).
157 -- A floating literal stands for an application of 'fromRational'
158 -- to a value of type 'Rational', so such literals have type
159 -- @('Fractional' a) => a@.
160 fromRational :: Rational -> a
167 -- | Extracting components of fractions.
169 -- Minimal complete definition: 'properFraction'
170 class (Real a, Fractional a) => RealFrac a where
171 -- | The function 'properFraction' takes a real fractional number @x@
172 -- and returns a pair @(n,f)@ such that @x = n+f@, and:
174 -- * @n@ is an integral number with the same sign as @x@; and
176 -- * @f@ is a fraction with the same type and sign as @x@,
177 -- and with absolute value less than @1@.
179 -- The default definitions of the 'ceiling', 'floor', 'truncate'
180 -- and 'round' functions are in terms of 'properFraction'.
181 properFraction :: (Integral b) => a -> (b,a)
182 -- | @'truncate' x@ returns the integer nearest @x@ between zero and @x@
183 truncate :: (Integral b) => a -> b
184 -- | @'round' x@ returns the nearest integer to @x@;
185 -- the even integer if @x@ is equidistant between two integers
186 round :: (Integral b) => a -> b
187 -- | @'ceiling' x@ returns the least integer not less than @x@
188 ceiling :: (Integral b) => a -> b
189 -- | @'floor' x@ returns the greatest integer not greater than @x@
190 floor :: (Integral b) => a -> b
192 {-# INLINE truncate #-}
193 truncate x = m where (m,_) = properFraction x
195 round x = let (n,r) = properFraction x
196 m = if r < 0 then n - 1 else n + 1
197 in case signum (abs r - 0.5) of
199 0 -> if even n then n else m
201 _ -> error "round default defn: Bad value"
203 ceiling x = if r > 0 then n + 1 else n
204 where (n,r) = properFraction x
206 floor x = if r < 0 then n - 1 else n
207 where (n,r) = properFraction x
211 These 'numeric' enumerations come straight from the Report
214 numericEnumFrom :: (Fractional a) => a -> [a]
215 numericEnumFrom n = n `seq` (n : numericEnumFrom (n + 1))
217 numericEnumFromThen :: (Fractional a) => a -> a -> [a]
218 numericEnumFromThen n m = n `seq` m `seq` (n : numericEnumFromThen m (m+m-n))
220 numericEnumFromTo :: (Ord a, Fractional a) => a -> a -> [a]
221 numericEnumFromTo n m = takeWhile (<= m + 1/2) (numericEnumFrom n)
223 numericEnumFromThenTo :: (Ord a, Fractional a) => a -> a -> a -> [a]
224 numericEnumFromThenTo e1 e2 e3
225 = takeWhile predicate (numericEnumFromThen e1 e2)
228 predicate | e2 >= e1 = (<= e3 + mid)
229 | otherwise = (>= e3 + mid)
233 %*********************************************************
235 \subsection{Instances for @Int@}
237 %*********************************************************
240 instance Real Int where
241 toRational x = toInteger x % 1
243 instance Integral Int where
244 toInteger (I# i) = smallInteger i
247 | b == 0 = divZeroError
248 | a == minBound && b == (-1) = overflowError
249 | otherwise = a `quotInt` b
252 | b == 0 = divZeroError
253 | a == minBound && b == (-1) = overflowError
254 | otherwise = a `remInt` b
257 | b == 0 = divZeroError
258 | a == minBound && b == (-1) = overflowError
259 | otherwise = a `divInt` b
262 | b == 0 = divZeroError
263 | a == minBound && b == (-1) = overflowError
264 | otherwise = a `modInt` b
267 | b == 0 = divZeroError
268 | a == minBound && b == (-1) = overflowError
269 | otherwise = a `quotRemInt` b
272 | b == 0 = divZeroError
273 | a == minBound && b == (-1) = overflowError
274 | otherwise = a `divModInt` b
278 %*********************************************************
280 \subsection{Instances for @Integer@}
282 %*********************************************************
285 instance Real Integer where
288 instance Integral Integer where
291 _ `quot` 0 = divZeroError
292 n `quot` d = n `quotInteger` d
294 _ `rem` 0 = divZeroError
295 n `rem` d = n `remInteger` d
297 _ `divMod` 0 = divZeroError
298 a `divMod` b = case a `divModInteger` b of
301 _ `quotRem` 0 = divZeroError
302 a `quotRem` b = case a `quotRemInteger` b of
305 -- use the defaults for div & mod
309 %*********************************************************
311 \subsection{Instances for @Ratio@}
313 %*********************************************************
316 instance (Integral a) => Ord (Ratio a) where
317 {-# SPECIALIZE instance Ord Rational #-}
318 (x:%y) <= (x':%y') = x * y' <= x' * y
319 (x:%y) < (x':%y') = x * y' < x' * y
321 instance (Integral a) => Num (Ratio a) where
322 {-# SPECIALIZE instance Num Rational #-}
323 (x:%y) + (x':%y') = reduce (x*y' + x'*y) (y*y')
324 (x:%y) - (x':%y') = reduce (x*y' - x'*y) (y*y')
325 (x:%y) * (x':%y') = reduce (x * x') (y * y')
326 negate (x:%y) = (-x) :% y
327 abs (x:%y) = abs x :% y
328 signum (x:%_) = signum x :% 1
329 fromInteger x = fromInteger x :% 1
331 {-# RULES "fromRational/id" fromRational = id :: Rational -> Rational #-}
332 instance (Integral a) => Fractional (Ratio a) where
333 {-# SPECIALIZE instance Fractional Rational #-}
334 (x:%y) / (x':%y') = (x*y') % (y*x')
335 recip (0:%_) = error "Ratio.%: zero denominator"
337 | x < 0 = negate y :% negate x
339 fromRational (x:%y) = fromInteger x % fromInteger y
341 instance (Integral a) => Real (Ratio a) where
342 {-# SPECIALIZE instance Real Rational #-}
343 toRational (x:%y) = toInteger x :% toInteger y
345 instance (Integral a) => RealFrac (Ratio a) where
346 {-# SPECIALIZE instance RealFrac Rational #-}
347 properFraction (x:%y) = (fromInteger (toInteger q), r:%y)
348 where (q,r) = quotRem x y
350 instance (Integral a) => Show (Ratio a) where
351 {-# SPECIALIZE instance Show Rational #-}
352 showsPrec p (x:%y) = showParen (p > ratioPrec) $
353 showsPrec ratioPrec1 x .
355 -- H98 report has spaces round the %
356 -- but we removed them [May 04]
357 -- and added them again for consistency with
358 -- Haskell 98 [Sep 08, #1920]
359 showsPrec ratioPrec1 y
361 instance (Integral a) => Enum (Ratio a) where
362 {-# SPECIALIZE instance Enum Rational #-}
366 toEnum n = fromIntegral n :% 1
367 fromEnum = fromInteger . truncate
369 enumFrom = numericEnumFrom
370 enumFromThen = numericEnumFromThen
371 enumFromTo = numericEnumFromTo
372 enumFromThenTo = numericEnumFromThenTo
376 %*********************************************************
378 \subsection{Coercions}
380 %*********************************************************
383 -- | general coercion from integral types
384 fromIntegral :: (Integral a, Num b) => a -> b
385 fromIntegral = fromInteger . toInteger
388 "fromIntegral/Int->Int" fromIntegral = id :: Int -> Int
391 -- | general coercion to fractional types
392 realToFrac :: (Real a, Fractional b) => a -> b
393 realToFrac = fromRational . toRational
396 "realToFrac/Int->Int" realToFrac = id :: Int -> Int
400 %*********************************************************
402 \subsection{Overloaded numeric functions}
404 %*********************************************************
407 -- | Converts a possibly-negative 'Real' value to a string.
408 showSigned :: (Real a)
409 => (a -> ShowS) -- ^ a function that can show unsigned values
410 -> Int -- ^ the precedence of the enclosing context
411 -> a -- ^ the value to show
413 showSigned showPos p x
414 | x < 0 = showParen (p > 6) (showChar '-' . showPos (-x))
415 | otherwise = showPos x
417 even, odd :: (Integral a) => a -> Bool
418 even n = n `rem` 2 == 0
421 -------------------------------------------------------
422 -- | raise a number to a non-negative integral power
423 {-# SPECIALISE (^) ::
424 Integer -> Integer -> Integer,
425 Integer -> Int -> Integer,
426 Int -> Int -> Int #-}
427 {-# INLINABLE (^) #-} -- See Note [Inlining (^)]
428 (^) :: (Num a, Integral b) => a -> b -> a
429 x0 ^ y0 | y0 < 0 = error "Negative exponent"
431 | otherwise = f x0 y0
432 where -- f : x0 ^ y0 = x ^ y
433 f x y | even y = f (x * x) (y `quot` 2)
435 | otherwise = g (x * x) ((y - 1) `quot` 2) x
436 -- g : x0 ^ y0 = (x ^ y) * z
437 g x y z | even y = g (x * x) (y `quot` 2) z
439 | otherwise = g (x * x) ((y - 1) `quot` 2) (x * z)
441 -- | raise a number to an integral power
442 (^^) :: (Fractional a, Integral b) => a -> b -> a
443 {-# INLINABLE (^^) #-} -- See Note [Inlining (^)
444 x ^^ n = if n >= 0 then x^n else recip (x^(negate n))
446 {- Note [Inlining (^)
447 ~~~~~~~~~~~~~~~~~~~~~
448 The INLINABLE pragma allows (^) to be specialised at its call sites.
449 If it is called repeatedly at the same type, that can make a huge
450 difference, because of those constants which can be repeatedly
453 Currently the fromInteger calls are not floated because we get
455 after the gentle round of simplification. -}
457 -------------------------------------------------------
458 -- Special power functions for Rational
463 -- For a legitimate Rational (n :% d), the numerator and denominator are
464 -- coprime, i.e. they have no common prime factor.
465 -- Therefore all powers (n ^ a) and (d ^ b) are also coprime, so it is
466 -- not necessary to compute the greatest common divisor, which would be
467 -- done in the default implementation at each multiplication step.
468 -- Since exponentiation quickly leads to very large numbers and
469 -- calculation of gcds is generally very slow for large numbers,
470 -- avoiding the gcd leads to an order of magnitude speedup relatively
471 -- soon (and an asymptotic improvement overall).
474 -- We cannot use these functions for general Ratio a because that would
475 -- change results in a multitude of cases.
476 -- The cause is that if a and b are coprime, their remainders by any
477 -- positive modulus generally aren't, so in the default implementation
481 -- (17 % 3) ^ 3 :: Ratio Word8
483 -- (17 % 3) ^ 3 = ((17 % 3) ^ 2) * (17 % 3)
484 -- = ((289 `mod` 256) % 9) * (17 % 3)
485 -- = (33 % 9) * (17 % 3)
486 -- = (11 % 3) * (17 % 3)
489 -- ((17^3) `mod` 256) % (3^3) = (4913 `mod` 256) % 27
493 -- Find out whether special-casing for numerator, denominator or
494 -- exponent = 1 (or -1, where that may apply) gains something.
496 -- Special version of (^) for Rational base
497 {-# RULES "(^)/Rational" (^) = (^%^) #-}
498 (^%^) :: Integral a => Rational -> a -> Rational
500 | e < 0 = error "Negative exponent"
502 | otherwise = (n ^ e) :% (d ^ e)
504 -- Special version of (^^) for Rational base
505 {-# RULES "(^^)/Rational" (^^) = (^^%^^) #-}
506 (^^%^^) :: Integral a => Rational -> a -> Rational
508 | e > 0 = (n ^ e) :% (d ^ e)
510 | n > 0 = (d ^ (negate e)) :% (n ^ (negate e))
511 | n == 0 = error "Ratio.%: zero denominator"
512 | otherwise = let nn = d ^ (negate e)
513 dd = (negate n) ^ (negate e)
514 in if even e then (nn :% dd) else (negate nn :% dd)
516 -------------------------------------------------------
517 -- | @'gcd' x y@ is the greatest (positive) integer that divides both @x@
518 -- and @y@; for example @'gcd' (-3) 6@ = @3@, @'gcd' (-3) (-6)@ = @3@,
519 -- @'gcd' 0 4@ = @4@. @'gcd' 0 0@ raises a runtime error.
520 gcd :: (Integral a) => a -> a -> a
521 gcd 0 0 = error "Prelude.gcd: gcd 0 0 is undefined"
522 gcd x y = gcd' (abs x) (abs y)
524 gcd' a b = gcd' b (a `rem` b)
526 -- | @'lcm' x y@ is the smallest positive integer that both @x@ and @y@ divide.
527 lcm :: (Integral a) => a -> a -> a
528 {-# SPECIALISE lcm :: Int -> Int -> Int #-}
531 lcm x y = abs ((x `quot` (gcd x y)) * y)
533 #ifdef OPTIMISE_INTEGER_GCD_LCM
535 "gcd/Int->Int->Int" gcd = gcdInt
536 "gcd/Integer->Integer->Integer" gcd = gcdInteger'
537 "lcm/Integer->Integer->Integer" lcm = lcmInteger
540 gcdInteger' :: Integer -> Integer -> Integer
541 gcdInteger' 0 0 = error "GHC.Real.gcdInteger': gcd 0 0 is undefined"
542 gcdInteger' a b = gcdInteger a b
544 gcdInt :: Int -> Int -> Int
545 gcdInt 0 0 = error "GHC.Real.gcdInt: gcd 0 0 is undefined"
546 gcdInt a b = fromIntegral (gcdInteger (fromIntegral a) (fromIntegral b))
549 integralEnumFrom :: (Integral a, Bounded a) => a -> [a]
550 integralEnumFrom n = map fromInteger [toInteger n .. toInteger (maxBound `asTypeOf` n)]
552 integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a]
553 integralEnumFromThen n1 n2
554 | i_n2 >= i_n1 = map fromInteger [i_n1, i_n2 .. toInteger (maxBound `asTypeOf` n1)]
555 | otherwise = map fromInteger [i_n1, i_n2 .. toInteger (minBound `asTypeOf` n1)]
560 integralEnumFromTo :: Integral a => a -> a -> [a]
561 integralEnumFromTo n m = map fromInteger [toInteger n .. toInteger m]
563 integralEnumFromThenTo :: Integral a => a -> a -> a -> [a]
564 integralEnumFromThenTo n1 n2 m
565 = map fromInteger [toInteger n1, toInteger n2 .. toInteger m]