2 {-# OPTIONS_GHC -fno-implicit-prelude #-}
3 -----------------------------------------------------------------------------
6 -- Copyright : (c) The FFI Task Force, 1994-2002
7 -- License : see libraries/base/LICENSE
9 -- Maintainer : cvs-ghc@haskell.org
10 -- Stability : internal
11 -- Portability : non-portable (GHC Extensions)
13 -- The types 'Ratio' and 'Rational', and the classes 'Real', 'Fractional',
14 -- 'Integral', and 'RealFrac'.
16 -----------------------------------------------------------------------------
21 import {-# SOURCE #-} GHC.Err
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
192 ceiling x = if r > 0 then n + 1 else n
193 where (n,r) = properFraction x
195 floor x = if r < 0 then n - 1 else n
196 where (n,r) = properFraction x
200 These 'numeric' enumerations come straight from the Report
203 numericEnumFrom :: (Fractional a) => a -> [a]
204 numericEnumFrom = iterate (+1)
206 numericEnumFromThen :: (Fractional a) => a -> a -> [a]
207 numericEnumFromThen n m = iterate (+(m-n)) n
209 numericEnumFromTo :: (Ord a, Fractional a) => a -> a -> [a]
210 numericEnumFromTo n m = takeWhile (<= m + 1/2) (numericEnumFrom n)
212 numericEnumFromThenTo :: (Ord a, Fractional a) => a -> a -> a -> [a]
213 numericEnumFromThenTo e1 e2 e3 = takeWhile pred (numericEnumFromThen e1 e2)
216 pred | e2 >= e1 = (<= e3 + mid)
217 | otherwise = (>= e3 + mid)
221 %*********************************************************
223 \subsection{Instances for @Int@}
225 %*********************************************************
228 instance Real Int where
229 toRational x = toInteger x % 1
231 instance Integral Int where
232 toInteger i = int2Integer i -- give back a full-blown Integer
235 | b == 0 = divZeroError
236 | a == minBound && b == (-1) = overflowError
237 | otherwise = a `quotInt` b
240 | b == 0 = divZeroError
241 | a == minBound && b == (-1) = overflowError
242 | otherwise = a `remInt` b
245 | b == 0 = divZeroError
246 | a == minBound && b == (-1) = overflowError
247 | otherwise = a `divInt` b
250 | b == 0 = divZeroError
251 | a == minBound && b == (-1) = overflowError
252 | otherwise = a `modInt` b
255 | b == 0 = divZeroError
256 | a == minBound && b == (-1) = overflowError
257 | otherwise = a `quotRemInt` b
260 | b == 0 = divZeroError
261 | a == minBound && b == (-1) = overflowError
262 | otherwise = a `divModInt` b
266 %*********************************************************
268 \subsection{Instances for @Integer@}
270 %*********************************************************
273 instance Real Integer where
276 instance Integral Integer where
279 a `quot` 0 = divZeroError
280 n `quot` d = n `quotInteger` d
282 a `rem` 0 = divZeroError
283 n `rem` d = n `remInteger` d
285 a `divMod` 0 = divZeroError
286 a `divMod` b = a `divModInteger` b
288 a `quotRem` 0 = divZeroError
289 a `quotRem` b = a `quotRemInteger` b
291 -- use the defaults for div & mod
295 %*********************************************************
297 \subsection{Instances for @Ratio@}
299 %*********************************************************
302 instance (Integral a) => Ord (Ratio a) where
303 {-# SPECIALIZE instance Ord Rational #-}
304 (x:%y) <= (x':%y') = x * y' <= x' * y
305 (x:%y) < (x':%y') = x * y' < x' * y
307 instance (Integral a) => Num (Ratio a) where
308 {-# SPECIALIZE instance Num Rational #-}
309 (x:%y) + (x':%y') = reduce (x*y' + x'*y) (y*y')
310 (x:%y) - (x':%y') = reduce (x*y' - x'*y) (y*y')
311 (x:%y) * (x':%y') = reduce (x * x') (y * y')
312 negate (x:%y) = (-x) :% y
313 abs (x:%y) = abs x :% y
314 signum (x:%_) = signum x :% 1
315 fromInteger x = fromInteger x :% 1
317 instance (Integral a) => Fractional (Ratio a) where
318 {-# SPECIALIZE instance Fractional Rational #-}
319 (x:%y) / (x':%y') = (x*y') % (y*x')
321 fromRational (x:%y) = fromInteger x :% fromInteger y
323 instance (Integral a) => Real (Ratio a) where
324 {-# SPECIALIZE instance Real Rational #-}
325 toRational (x:%y) = toInteger x :% toInteger y
327 instance (Integral a) => RealFrac (Ratio a) where
328 {-# SPECIALIZE instance RealFrac Rational #-}
329 properFraction (x:%y) = (fromInteger (toInteger q), r:%y)
330 where (q,r) = quotRem x y
332 instance (Integral a) => Show (Ratio a) where
333 {-# SPECIALIZE instance Show Rational #-}
334 showsPrec p (x:%y) = showParen (p > ratioPrec) $
335 showsPrec ratioPrec1 x .
336 showString "%" . -- H98 report has spaces round the %
337 -- but we removed them [May 04]
338 showsPrec ratioPrec1 y
340 instance (Integral a) => Enum (Ratio a) where
341 {-# SPECIALIZE instance Enum Rational #-}
345 toEnum n = fromInteger (int2Integer n) :% 1
346 fromEnum = fromInteger . truncate
348 enumFrom = numericEnumFrom
349 enumFromThen = numericEnumFromThen
350 enumFromTo = numericEnumFromTo
351 enumFromThenTo = numericEnumFromThenTo
355 %*********************************************************
357 \subsection{Coercions}
359 %*********************************************************
362 -- | general coercion from integral types
363 fromIntegral :: (Integral a, Num b) => a -> b
364 fromIntegral = fromInteger . toInteger
367 "fromIntegral/Int->Int" fromIntegral = id :: Int -> Int
370 -- | general coercion to fractional types
371 realToFrac :: (Real a, Fractional b) => a -> b
372 realToFrac = fromRational . toRational
375 "realToFrac/Int->Int" realToFrac = id :: Int -> Int
379 %*********************************************************
381 \subsection{Overloaded numeric functions}
383 %*********************************************************
386 -- | Converts a possibly-negative 'Real' value to a string.
387 showSigned :: (Real a)
388 => (a -> ShowS) -- ^ a function that can show unsigned values
389 -> Int -- ^ the precedence of the enclosing context
390 -> a -- ^ the value to show
392 showSigned showPos p x
393 | x < 0 = showParen (p > 6) (showChar '-' . showPos (-x))
394 | otherwise = showPos x
396 even, odd :: (Integral a) => a -> Bool
397 even n = n `rem` 2 == 0
400 -------------------------------------------------------
401 -- | raise a number to a non-negative integral power
402 {-# SPECIALISE (^) ::
403 Integer -> Integer -> Integer,
404 Integer -> Int -> Integer,
405 Int -> Int -> Int #-}
406 (^) :: (Num a, Integral b) => a -> b -> a
408 x ^ n | n > 0 = f x (n-1) x
410 f a d y = g a d where
411 g b i | even i = g (b*b) (i `quot` 2)
412 | otherwise = f b (i-1) (b*y)
413 _ ^ _ = error "Prelude.^: negative exponent"
415 -- | raise a number to an integral power
416 {-# SPECIALISE (^^) ::
417 Rational -> Int -> Rational #-}
418 (^^) :: (Fractional a, Integral b) => a -> b -> a
419 x ^^ n = if n >= 0 then x^n else recip (x^(negate n))
422 -------------------------------------------------------
423 -- | @'gcd' x y@ is the greatest (positive) integer that divides both @x@
424 -- and @y@; for example @'gcd' (-3) 6@ = @3@, @'gcd' (-3) (-6)@ = @3@,
425 -- @'gcd' 0 4@ = @4@. @'gcd' 0 0@ raises a runtime error.
426 gcd :: (Integral a) => a -> a -> a
427 gcd 0 0 = error "Prelude.gcd: gcd 0 0 is undefined"
428 gcd x y = gcd' (abs x) (abs y)
430 gcd' a b = gcd' b (a `rem` b)
432 -- | @'lcm' x y@ is the smallest positive integer that both @x@ and @y@ divide.
433 lcm :: (Integral a) => a -> a -> a
434 {-# SPECIALISE lcm :: Int -> Int -> Int #-}
437 lcm x y = abs ((x `quot` (gcd x y)) * y)
441 "gcd/Int->Int->Int" gcd = gcdInt
442 "gcd/Integer->Integer->Integer" gcd = gcdInteger
443 "lcm/Integer->Integer->Integer" lcm = lcmInteger
446 integralEnumFrom :: (Integral a, Bounded a) => a -> [a]
447 integralEnumFrom n = map fromInteger [toInteger n .. toInteger (maxBound `asTypeOf` n)]
449 integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a]
450 integralEnumFromThen n1 n2
451 | i_n2 >= i_n1 = map fromInteger [i_n1, i_n2 .. toInteger (maxBound `asTypeOf` n1)]
452 | otherwise = map fromInteger [i_n1, i_n2 .. toInteger (minBound `asTypeOf` n1)]
457 integralEnumFromTo :: Integral a => a -> a -> [a]
458 integralEnumFromTo n m = map fromInteger [toInteger n .. toInteger m]
460 integralEnumFromThenTo :: Integral a => a -> a -> a -> [a]
461 integralEnumFromThenTo n1 n2 m
462 = map fromInteger [toInteger n1, toInteger n2 .. toInteger m]