2 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
3 {-# OPTIONS_HADDOCK hide #-}
4 -----------------------------------------------------------------------------
7 -- Copyright : (c) The FFI Task Force, 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
136 n `quot` d = q where (q,_) = quotRem n d
137 n `rem` d = r where (_,r) = quotRem n d
138 n `div` d = q where (q,_) = divMod n d
139 n `mod` d = r where (_,r) = divMod n d
140 divMod n d = if signum r == negate (signum d) then (q-1, r+d) else qr
141 where qr@(q,r) = quotRem n d
143 -- | Fractional numbers, supporting real division.
145 -- Minimal complete definition: 'fromRational' and ('recip' or @('/')@)
146 class (Num a) => Fractional a where
147 -- | fractional division
149 -- | reciprocal fraction
151 -- | Conversion from a 'Rational' (that is @'Ratio' 'Integer'@).
152 -- A floating literal stands for an application of 'fromRational'
153 -- to a value of type 'Rational', so such literals have type
154 -- @('Fractional' a) => a@.
155 fromRational :: Rational -> a
160 -- | Extracting components of fractions.
162 -- Minimal complete definition: 'properFraction'
163 class (Real a, Fractional a) => RealFrac a where
164 -- | The function 'properFraction' takes a real fractional number @x@
165 -- and returns a pair @(n,f)@ such that @x = n+f@, and:
167 -- * @n@ is an integral number with the same sign as @x@; and
169 -- * @f@ is a fraction with the same type and sign as @x@,
170 -- and with absolute value less than @1@.
172 -- The default definitions of the 'ceiling', 'floor', 'truncate'
173 -- and 'round' functions are in terms of 'properFraction'.
174 properFraction :: (Integral b) => a -> (b,a)
175 -- | @'truncate' x@ returns the integer nearest @x@ between zero and @x@
176 truncate :: (Integral b) => a -> b
177 -- | @'round' x@ returns the nearest integer to @x@;
178 -- the even integer if @x@ is equidistant between two integers
179 round :: (Integral b) => a -> b
180 -- | @'ceiling' x@ returns the least integer not less than @x@
181 ceiling :: (Integral b) => a -> b
182 -- | @'floor' x@ returns the greatest integer not greater than @x@
183 floor :: (Integral b) => a -> b
185 truncate x = m where (m,_) = properFraction x
187 round x = let (n,r) = properFraction x
188 m = if r < 0 then n - 1 else n + 1
189 in case signum (abs r - 0.5) of
191 0 -> if even n then n else m
193 _ -> error "round default defn: Bad value"
195 ceiling x = if r > 0 then n + 1 else n
196 where (n,r) = properFraction x
198 floor x = if r < 0 then n - 1 else n
199 where (n,r) = properFraction x
203 These 'numeric' enumerations come straight from the Report
206 numericEnumFrom :: (Fractional a) => a -> [a]
207 numericEnumFrom n = n `seq` (n : numericEnumFrom (n + 1))
209 numericEnumFromThen :: (Fractional a) => a -> a -> [a]
210 numericEnumFromThen n m = n `seq` m `seq` (n : numericEnumFromThen m (m+m-n))
212 numericEnumFromTo :: (Ord a, Fractional a) => a -> a -> [a]
213 numericEnumFromTo n m = takeWhile (<= m + 1/2) (numericEnumFrom n)
215 numericEnumFromThenTo :: (Ord a, Fractional a) => a -> a -> a -> [a]
216 numericEnumFromThenTo e1 e2 e3
217 = takeWhile predicate (numericEnumFromThen e1 e2)
220 predicate | e2 >= e1 = (<= e3 + mid)
221 | otherwise = (>= e3 + mid)
225 %*********************************************************
227 \subsection{Instances for @Int@}
229 %*********************************************************
232 instance Real Int where
233 toRational x = toInteger x % 1
235 instance Integral Int where
236 toInteger (I# i) = smallInteger i
239 | b == 0 = divZeroError
240 | a == minBound && b == (-1) = overflowError
241 | otherwise = a `quotInt` b
244 | b == 0 = divZeroError
245 | a == minBound && b == (-1) = overflowError
246 | otherwise = a `remInt` b
249 | b == 0 = divZeroError
250 | a == minBound && b == (-1) = overflowError
251 | otherwise = a `divInt` b
254 | b == 0 = divZeroError
255 | a == minBound && b == (-1) = overflowError
256 | otherwise = a `modInt` b
259 | b == 0 = divZeroError
260 | a == minBound && b == (-1) = overflowError
261 | otherwise = a `quotRemInt` b
264 | b == 0 = divZeroError
265 | a == minBound && b == (-1) = overflowError
266 | otherwise = a `divModInt` b
270 %*********************************************************
272 \subsection{Instances for @Integer@}
274 %*********************************************************
277 instance Real Integer where
280 instance Integral Integer where
283 _ `quot` 0 = divZeroError
284 n `quot` d = n `quotInteger` d
286 _ `rem` 0 = divZeroError
287 n `rem` d = n `remInteger` d
289 _ `divMod` 0 = divZeroError
290 a `divMod` b = case a `divModInteger` b of
293 _ `quotRem` 0 = divZeroError
294 a `quotRem` b = case a `quotRemInteger` b of
297 -- use the defaults for div & mod
301 %*********************************************************
303 \subsection{Instances for @Ratio@}
305 %*********************************************************
308 instance (Integral a) => Ord (Ratio a) where
309 {-# SPECIALIZE instance Ord Rational #-}
310 (x:%y) <= (x':%y') = x * y' <= x' * y
311 (x:%y) < (x':%y') = x * y' < x' * y
313 instance (Integral a) => Num (Ratio a) where
314 {-# SPECIALIZE instance Num Rational #-}
315 (x:%y) + (x':%y') = reduce (x*y' + x'*y) (y*y')
316 (x:%y) - (x':%y') = reduce (x*y' - x'*y) (y*y')
317 (x:%y) * (x':%y') = reduce (x * x') (y * y')
318 negate (x:%y) = (-x) :% y
319 abs (x:%y) = abs x :% y
320 signum (x:%_) = signum x :% 1
321 fromInteger x = fromInteger x :% 1
323 instance (Integral a) => Fractional (Ratio a) where
324 {-# SPECIALIZE instance Fractional Rational #-}
325 (x:%y) / (x':%y') = (x*y') % (y*x')
327 fromRational (x:%y) = fromInteger x :% fromInteger y
329 instance (Integral a) => Real (Ratio a) where
330 {-# SPECIALIZE instance Real Rational #-}
331 toRational (x:%y) = toInteger x :% toInteger y
333 instance (Integral a) => RealFrac (Ratio a) where
334 {-# SPECIALIZE instance RealFrac Rational #-}
335 properFraction (x:%y) = (fromInteger (toInteger q), r:%y)
336 where (q,r) = quotRem x y
338 instance (Integral a) => Show (Ratio a) where
339 {-# SPECIALIZE instance Show Rational #-}
340 showsPrec p (x:%y) = showParen (p > ratioPrec) $
341 showsPrec ratioPrec1 x .
343 -- H98 report has spaces round the %
344 -- but we removed them [May 04]
345 -- and added them again for consistency with
346 -- Haskell 98 [Sep 08, #1920]
347 showsPrec ratioPrec1 y
349 instance (Integral a) => Enum (Ratio a) where
350 {-# SPECIALIZE instance Enum Rational #-}
354 toEnum n = fromIntegral n :% 1
355 fromEnum = fromInteger . truncate
357 enumFrom = numericEnumFrom
358 enumFromThen = numericEnumFromThen
359 enumFromTo = numericEnumFromTo
360 enumFromThenTo = numericEnumFromThenTo
364 %*********************************************************
366 \subsection{Coercions}
368 %*********************************************************
371 -- | general coercion from integral types
372 fromIntegral :: (Integral a, Num b) => a -> b
373 fromIntegral = fromInteger . toInteger
376 "fromIntegral/Int->Int" fromIntegral = id :: Int -> Int
379 -- | general coercion to fractional types
380 realToFrac :: (Real a, Fractional b) => a -> b
381 realToFrac = fromRational . toRational
384 "realToFrac/Int->Int" realToFrac = id :: Int -> Int
388 %*********************************************************
390 \subsection{Overloaded numeric functions}
392 %*********************************************************
395 -- | Converts a possibly-negative 'Real' value to a string.
396 showSigned :: (Real a)
397 => (a -> ShowS) -- ^ a function that can show unsigned values
398 -> Int -- ^ the precedence of the enclosing context
399 -> a -- ^ the value to show
401 showSigned showPos p x
402 | x < 0 = showParen (p > 6) (showChar '-' . showPos (-x))
403 | otherwise = showPos x
405 even, odd :: (Integral a) => a -> Bool
406 even n = n `rem` 2 == 0
409 -------------------------------------------------------
410 -- | raise a number to a non-negative integral power
411 {-# SPECIALISE (^) ::
412 Integer -> Integer -> Integer,
413 Integer -> Int -> Integer,
414 Int -> Int -> Int #-}
415 (^) :: (Num a, Integral b) => a -> b -> a
416 x0 ^ y0 | y0 < 0 = error "Negative exponent"
418 | otherwise = f x0 y0
419 where -- f : x0 ^ y0 = x ^ y
420 f x y | even y = f (x * x) (y `quot` 2)
422 | otherwise = g (x * x) ((y - 1) `quot` 2) x
423 -- g : x0 ^ y0 = (x ^ y) * z
424 g x y z | even y = g (x * x) (y `quot` 2) z
426 | otherwise = g (x * x) ((y - 1) `quot` 2) (x * z)
428 -- | raise a number to an integral power
429 {-# SPECIALISE (^^) ::
430 Rational -> Int -> Rational #-}
431 (^^) :: (Fractional a, Integral b) => a -> b -> a
432 x ^^ n = if n >= 0 then x^n else recip (x^(negate n))
435 -------------------------------------------------------
436 -- | @'gcd' x y@ is the greatest (positive) integer that divides both @x@
437 -- and @y@; for example @'gcd' (-3) 6@ = @3@, @'gcd' (-3) (-6)@ = @3@,
438 -- @'gcd' 0 4@ = @4@. @'gcd' 0 0@ raises a runtime error.
439 gcd :: (Integral a) => a -> a -> a
440 gcd 0 0 = error "Prelude.gcd: gcd 0 0 is undefined"
441 gcd x y = gcd' (abs x) (abs y)
443 gcd' a b = gcd' b (a `rem` b)
445 -- | @'lcm' x y@ is the smallest positive integer that both @x@ and @y@ divide.
446 lcm :: (Integral a) => a -> a -> a
447 {-# SPECIALISE lcm :: Int -> Int -> Int #-}
450 lcm x y = abs ((x `quot` (gcd x y)) * y)
453 "gcd/Int->Int->Int" gcd = gcdInt
454 "gcd/Integer->Integer->Integer" gcd = gcdInteger'
455 "lcm/Integer->Integer->Integer" lcm = lcmInteger
458 -- XXX to use another Integer implementation, you might need to disable
459 -- the gcd/Integer and lcm/Integer RULES above
461 gcdInteger' :: Integer -> Integer -> Integer
462 gcdInteger' 0 0 = error "GHC.Real.gcdInteger': gcd 0 0 is undefined"
463 gcdInteger' a b = gcdInteger a b
465 gcdInt :: Int -> Int -> Int
466 gcdInt 0 0 = error "GHC.Real.gcdInt: gcd 0 0 is undefined"
467 gcdInt a b = fromIntegral (gcdInteger (fromIntegral a) (fromIntegral b))
469 integralEnumFrom :: (Integral a, Bounded a) => a -> [a]
470 integralEnumFrom n = map fromInteger [toInteger n .. toInteger (maxBound `asTypeOf` n)]
472 integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a]
473 integralEnumFromThen n1 n2
474 | i_n2 >= i_n1 = map fromInteger [i_n1, i_n2 .. toInteger (maxBound `asTypeOf` n1)]
475 | otherwise = map fromInteger [i_n1, i_n2 .. toInteger (minBound `asTypeOf` n1)]
480 integralEnumFromTo :: Integral a => a -> a -> [a]
481 integralEnumFromTo n m = map fromInteger [toInteger n .. toInteger m]
483 integralEnumFromThenTo :: Integral a => a -> a -> a -> [a]
484 integralEnumFromThenTo n1 n2 m
485 = map fromInteger [toInteger n1, toInteger n2 .. toInteger m]