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 -----------------------------------------------------------------------------
29 infixl 7 /, `quot`, `rem`, `div`, `mod`
32 default () -- Double isn't available yet,
33 -- and we shouldn't be using defaults anyway
37 %*********************************************************
39 \subsection{The @Ratio@ and @Rational@ types}
41 %*********************************************************
44 -- | Rational numbers, with numerator and denominator of some 'Integral' type.
45 data (Integral a) => Ratio a = !a :% !a deriving (Eq)
47 -- | Arbitrary-precision rational numbers, represented as a ratio of
48 -- two 'Integer' values. A rational number may be constructed using
50 type Rational = Ratio Integer
52 ratioPrec, ratioPrec1 :: Int
53 ratioPrec = 7 -- Precedence of ':%' constructor
54 ratioPrec1 = ratioPrec + 1
56 infinity, notANumber :: Rational
60 -- Use :%, not % for Inf/NaN; the latter would
61 -- immediately lead to a runtime error, because it normalises.
66 -- | Forms the ratio of two integral numbers.
67 {-# SPECIALISE (%) :: Integer -> Integer -> Rational #-}
68 (%) :: (Integral a) => a -> a -> Ratio a
70 -- | Extract the numerator of the ratio in reduced form:
71 -- the numerator and denominator have no common factor and the denominator
73 numerator :: (Integral a) => Ratio a -> a
75 -- | Extract the denominator of the ratio in reduced form:
76 -- the numerator and denominator have no common factor and the denominator
78 denominator :: (Integral a) => Ratio a -> a
81 \tr{reduce} is a subsidiary function used only in this module .
82 It normalises a ratio by dividing both numerator and denominator by
83 their greatest common divisor.
86 reduce :: (Integral a) => a -> a -> Ratio a
87 {-# SPECIALISE reduce :: Integer -> Integer -> Rational #-}
88 reduce _ 0 = error "Ratio.%: zero denominator"
89 reduce x y = (x `quot` d) :% (y `quot` d)
94 x % y = reduce (x * signum y) (abs y)
96 numerator (x :% _) = x
97 denominator (_ :% y) = y
101 %*********************************************************
103 \subsection{Standard numeric classes}
105 %*********************************************************
108 class (Num a, Ord a) => Real a where
109 -- | the rational equivalent of its real argument with full precision
110 toRational :: a -> Rational
112 -- | Integral numbers, supporting integer division.
114 -- Minimal complete definition: 'quotRem' and 'toInteger'
115 class (Real a, Enum a) => Integral a where
116 -- | integer division truncated toward zero
118 -- | integer remainder, satisfying
120 -- > (x `quot` y)*y + (x `rem` y) == x
122 -- | integer division truncated toward negative infinity
124 -- | integer modulus, satisfying
126 -- > (x `div` y)*y + (x `mod` y) == x
128 -- | simultaneous 'quot' and 'rem'
129 quotRem :: a -> a -> (a,a)
130 -- | simultaneous 'div' and 'mod'
131 divMod :: a -> a -> (a,a)
132 -- | conversion to 'Integer'
133 toInteger :: a -> Integer
135 n `quot` d = q where (q,_) = quotRem n d
136 n `rem` d = r where (_,r) = quotRem n d
137 n `div` d = q where (q,_) = divMod n d
138 n `mod` d = r where (_,r) = divMod n d
139 divMod n d = if signum r == negate (signum d) then (q-1, r+d) else qr
140 where qr@(q,r) = quotRem n d
142 -- | Fractional numbers, supporting real division.
144 -- Minimal complete definition: 'fromRational' and ('recip' or @('/')@)
145 class (Num a) => Fractional a where
146 -- | fractional division
148 -- | reciprocal fraction
150 -- | Conversion from a 'Rational' (that is @'Ratio' 'Integer'@).
151 -- A floating literal stands for an application of 'fromRational'
152 -- to a value of type 'Rational', so such literals have type
153 -- @('Fractional' a) => a@.
154 fromRational :: Rational -> a
159 -- | Extracting components of fractions.
161 -- Minimal complete definition: 'properFraction'
162 class (Real a, Fractional a) => RealFrac a where
163 -- | The function 'properFraction' takes a real fractional number @x@
164 -- and returns a pair @(n,f)@ such that @x = n+f@, and:
166 -- * @n@ is an integral number with the same sign as @x@; and
168 -- * @f@ is a fraction with the same type and sign as @x@,
169 -- and with absolute value less than @1@.
171 -- The default definitions of the 'ceiling', 'floor', 'truncate'
172 -- and 'round' functions are in terms of 'properFraction'.
173 properFraction :: (Integral b) => a -> (b,a)
174 -- | @'truncate' x@ returns the integer nearest @x@ between zero and @x@
175 truncate :: (Integral b) => a -> b
176 -- | @'round' x@ returns the nearest integer to @x@
177 round :: (Integral b) => a -> b
178 -- | @'ceiling' x@ returns the least integer not less than @x@
179 ceiling :: (Integral b) => a -> b
180 -- | @'floor' x@ returns the greatest integer not greater than @x@
181 floor :: (Integral b) => a -> b
183 truncate x = m where (m,_) = properFraction x
185 round x = let (n,r) = properFraction x
186 m = if r < 0 then n - 1 else n + 1
187 in case signum (abs r - 0.5) of
189 0 -> if even n then n else m
191 _ -> error "round default defn: Bad value"
193 ceiling x = if r > 0 then n + 1 else n
194 where (n,r) = properFraction x
196 floor x = if r < 0 then n - 1 else n
197 where (n,r) = properFraction x
201 These 'numeric' enumerations come straight from the Report
204 numericEnumFrom :: (Fractional a) => a -> [a]
205 numericEnumFrom n = n `seq` (n : numericEnumFrom (n + 1))
207 numericEnumFromThen :: (Fractional a) => a -> a -> [a]
208 numericEnumFromThen n m = n `seq` m `seq` (n : numericEnumFromThen m (m+m-n))
210 numericEnumFromTo :: (Ord a, Fractional a) => a -> a -> [a]
211 numericEnumFromTo n m = takeWhile (<= m + 1/2) (numericEnumFrom n)
213 numericEnumFromThenTo :: (Ord a, Fractional a) => a -> a -> a -> [a]
214 numericEnumFromThenTo e1 e2 e3
215 = takeWhile predicate (numericEnumFromThen e1 e2)
218 predicate | e2 >= e1 = (<= e3 + mid)
219 | otherwise = (>= e3 + mid)
223 %*********************************************************
225 \subsection{Instances for @Int@}
227 %*********************************************************
230 instance Real Int where
231 toRational x = toInteger x % 1
233 instance Integral Int where
234 toInteger (I# i) = smallInteger i
237 | b == 0 = divZeroError
238 | a == minBound && b == (-1) = overflowError
239 | otherwise = a `quotInt` b
242 | b == 0 = divZeroError
243 | a == minBound && b == (-1) = overflowError
244 | otherwise = a `remInt` b
247 | b == 0 = divZeroError
248 | a == minBound && b == (-1) = overflowError
249 | otherwise = a `divInt` b
252 | b == 0 = divZeroError
253 | a == minBound && b == (-1) = overflowError
254 | otherwise = a `modInt` b
257 | b == 0 = divZeroError
258 | a == minBound && b == (-1) = overflowError
259 | otherwise = a `quotRemInt` b
262 | b == 0 = divZeroError
263 | a == minBound && b == (-1) = overflowError
264 | otherwise = a `divModInt` b
268 %*********************************************************
270 \subsection{Instances for @Integer@}
272 %*********************************************************
275 instance Real Integer where
278 instance Integral Integer where
281 _ `quot` 0 = divZeroError
282 n `quot` d = n `quotInteger` d
284 _ `rem` 0 = divZeroError
285 n `rem` d = n `remInteger` d
287 _ `divMod` 0 = divZeroError
288 a `divMod` b = case a `divModInteger` b of
291 _ `quotRem` 0 = divZeroError
292 a `quotRem` b = case a `quotRemInteger` b of
295 -- use the defaults for div & mod
299 %*********************************************************
301 \subsection{Instances for @Ratio@}
303 %*********************************************************
306 instance (Integral a) => Ord (Ratio a) where
307 {-# SPECIALIZE instance Ord Rational #-}
308 (x:%y) <= (x':%y') = x * y' <= x' * y
309 (x:%y) < (x':%y') = x * y' < x' * y
311 instance (Integral a) => Num (Ratio a) where
312 {-# SPECIALIZE instance Num Rational #-}
313 (x:%y) + (x':%y') = reduce (x*y' + x'*y) (y*y')
314 (x:%y) - (x':%y') = reduce (x*y' - x'*y) (y*y')
315 (x:%y) * (x':%y') = reduce (x * x') (y * y')
316 negate (x:%y) = (-x) :% y
317 abs (x:%y) = abs x :% y
318 signum (x:%_) = signum x :% 1
319 fromInteger x = fromInteger x :% 1
321 instance (Integral a) => Fractional (Ratio a) where
322 {-# SPECIALIZE instance Fractional Rational #-}
323 (x:%y) / (x':%y') = (x*y') % (y*x')
325 fromRational (x:%y) = fromInteger x :% fromInteger y
327 instance (Integral a) => Real (Ratio a) where
328 {-# SPECIALIZE instance Real Rational #-}
329 toRational (x:%y) = toInteger x :% toInteger y
331 instance (Integral a) => RealFrac (Ratio a) where
332 {-# SPECIALIZE instance RealFrac Rational #-}
333 properFraction (x:%y) = (fromInteger (toInteger q), r:%y)
334 where (q,r) = quotRem x y
336 instance (Integral a) => Show (Ratio a) where
337 {-# SPECIALIZE instance Show Rational #-}
338 showsPrec p (x:%y) = showParen (p > ratioPrec) $
339 showsPrec ratioPrec1 x .
340 showString "%" . -- H98 report has spaces round the %
341 -- but we removed them [May 04]
342 showsPrec ratioPrec1 y
344 instance (Integral a) => Enum (Ratio a) where
345 {-# SPECIALIZE instance Enum Rational #-}
349 toEnum n = fromIntegral n :% 1
350 fromEnum = fromInteger . truncate
352 enumFrom = numericEnumFrom
353 enumFromThen = numericEnumFromThen
354 enumFromTo = numericEnumFromTo
355 enumFromThenTo = numericEnumFromThenTo
359 %*********************************************************
361 \subsection{Coercions}
363 %*********************************************************
366 -- | general coercion from integral types
367 fromIntegral :: (Integral a, Num b) => a -> b
368 fromIntegral = fromInteger . toInteger
371 "fromIntegral/Int->Int" fromIntegral = id :: Int -> Int
374 -- | general coercion to fractional types
375 realToFrac :: (Real a, Fractional b) => a -> b
376 realToFrac = fromRational . toRational
379 "realToFrac/Int->Int" realToFrac = id :: Int -> Int
383 %*********************************************************
385 \subsection{Overloaded numeric functions}
387 %*********************************************************
390 -- | Converts a possibly-negative 'Real' value to a string.
391 showSigned :: (Real a)
392 => (a -> ShowS) -- ^ a function that can show unsigned values
393 -> Int -- ^ the precedence of the enclosing context
394 -> a -- ^ the value to show
396 showSigned showPos p x
397 | x < 0 = showParen (p > 6) (showChar '-' . showPos (-x))
398 | otherwise = showPos x
400 even, odd :: (Integral a) => a -> Bool
401 even n = n `rem` 2 == 0
404 -------------------------------------------------------
405 -- | raise a number to a non-negative integral power
406 {-# SPECIALISE (^) ::
407 Integer -> Integer -> Integer,
408 Integer -> Int -> Integer,
409 Int -> Int -> Int #-}
410 (^) :: (Num a, Integral b) => a -> b -> a
411 x0 ^ y0 | y0 < 0 = error "Negative exponent"
413 | otherwise = f x0 y0
414 where -- f : x0 ^ y0 = x ^ y
415 f x y | even y = f (x * x) (y `quot` 2)
417 | otherwise = g (x * x) ((y - 1) `quot` 2) x
418 -- g : x0 ^ y0 = (x ^ y) * z
419 g x y z | even y = g (x * x) (y `quot` 2) z
421 | otherwise = g (x * x) ((y - 1) `quot` 2) (x * z)
423 -- | raise a number to an integral power
424 {-# SPECIALISE (^^) ::
425 Rational -> Int -> Rational #-}
426 (^^) :: (Fractional a, Integral b) => a -> b -> a
427 x ^^ n = if n >= 0 then x^n else recip (x^(negate n))
430 -------------------------------------------------------
431 -- | @'gcd' x y@ is the greatest (positive) integer that divides both @x@
432 -- and @y@; for example @'gcd' (-3) 6@ = @3@, @'gcd' (-3) (-6)@ = @3@,
433 -- @'gcd' 0 4@ = @4@. @'gcd' 0 0@ raises a runtime error.
434 gcd :: (Integral a) => a -> a -> a
435 gcd 0 0 = error "Prelude.gcd: gcd 0 0 is undefined"
436 gcd x y = gcd' (abs x) (abs y)
438 gcd' a b = gcd' b (a `rem` b)
440 -- | @'lcm' x y@ is the smallest positive integer that both @x@ and @y@ divide.
441 lcm :: (Integral a) => a -> a -> a
442 {-# SPECIALISE lcm :: Int -> Int -> Int #-}
445 lcm x y = abs ((x `quot` (gcd x y)) * y)
448 "gcd/Int->Int->Int" gcd = gcdInt
451 -- XXX these optimisation rules are disabled for now to make it easier
452 -- to experiment with other Integer implementations
453 -- "gcd/Integer->Integer->Integer" gcd = gcdInteger'
454 -- "lcm/Integer->Integer->Integer" lcm = lcmInteger
456 -- gcdInteger' :: Integer -> Integer -> Integer
457 -- gcdInteger' 0 0 = error "GHC.Real.gcdInteger': gcd 0 0 is undefined"
458 -- gcdInteger' a b = gcdInteger a b
460 integralEnumFrom :: (Integral a, Bounded a) => a -> [a]
461 integralEnumFrom n = map fromInteger [toInteger n .. toInteger (maxBound `asTypeOf` n)]
463 integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a]
464 integralEnumFromThen n1 n2
465 | i_n2 >= i_n1 = map fromInteger [i_n1, i_n2 .. toInteger (maxBound `asTypeOf` n1)]
466 | otherwise = map fromInteger [i_n1, i_n2 .. toInteger (minBound `asTypeOf` n1)]
471 integralEnumFromTo :: Integral a => a -> a -> [a]
472 integralEnumFromTo n m = map fromInteger [toInteger n .. toInteger m]
474 integralEnumFromThenTo :: Integral a => a -> a -> a -> [a]
475 integralEnumFromThenTo n1 n2 m
476 = map fromInteger [toInteger n1, toInteger n2 .. toInteger m]