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
234 a `quot` 0 = divZeroError
235 a `quot` b = a `quotInt` b
237 a `rem` 0 = divZeroError
238 a `rem` b = a `remInt` b
240 a `div` 0 = divZeroError
241 a `div` b = a `divInt` b
243 a `mod` 0 = divZeroError
244 a `mod` b = a `modInt` b
246 a `quotRem` 0 = divZeroError
247 a `quotRem` b = a `quotRemInt` b
249 a `divMod` 0 = divZeroError
250 a `divMod` b = a `divModInt` b
254 %*********************************************************
256 \subsection{Instances for @Integer@}
258 %*********************************************************
261 instance Real Integer where
264 instance Integral Integer where
267 a `quot` 0 = divZeroError
268 n `quot` d = n `quotInteger` d
270 a `rem` 0 = divZeroError
271 n `rem` d = n `remInteger` d
273 a `divMod` 0 = divZeroError
274 a `divMod` b = a `divModInteger` b
276 a `quotRem` 0 = divZeroError
277 a `quotRem` b = a `quotRemInteger` b
279 -- use the defaults for div & mod
283 %*********************************************************
285 \subsection{Instances for @Ratio@}
287 %*********************************************************
290 instance (Integral a) => Ord (Ratio a) where
291 {-# SPECIALIZE instance Ord Rational #-}
292 (x:%y) <= (x':%y') = x * y' <= x' * y
293 (x:%y) < (x':%y') = x * y' < x' * y
295 instance (Integral a) => Num (Ratio a) where
296 {-# SPECIALIZE instance Num Rational #-}
297 (x:%y) + (x':%y') = reduce (x*y' + x'*y) (y*y')
298 (x:%y) - (x':%y') = reduce (x*y' - x'*y) (y*y')
299 (x:%y) * (x':%y') = reduce (x * x') (y * y')
300 negate (x:%y) = (-x) :% y
301 abs (x:%y) = abs x :% y
302 signum (x:%_) = signum x :% 1
303 fromInteger x = fromInteger x :% 1
305 instance (Integral a) => Fractional (Ratio a) where
306 {-# SPECIALIZE instance Fractional Rational #-}
307 (x:%y) / (x':%y') = (x*y') % (y*x')
309 fromRational (x:%y) = fromInteger x :% fromInteger y
311 instance (Integral a) => Real (Ratio a) where
312 {-# SPECIALIZE instance Real Rational #-}
313 toRational (x:%y) = toInteger x :% toInteger y
315 instance (Integral a) => RealFrac (Ratio a) where
316 {-# SPECIALIZE instance RealFrac Rational #-}
317 properFraction (x:%y) = (fromInteger (toInteger q), r:%y)
318 where (q,r) = quotRem x y
320 instance (Integral a) => Show (Ratio a) where
321 {-# SPECIALIZE instance Show Rational #-}
322 showsPrec p (x:%y) = showParen (p > ratioPrec) $
323 showsPrec ratioPrec1 x .
324 showString "%" . -- H98 report has spaces round the %
325 -- but we removed them [May 04]
326 showsPrec ratioPrec1 y
328 instance (Integral a) => Enum (Ratio a) where
329 {-# SPECIALIZE instance Enum Rational #-}
333 toEnum n = fromInteger (int2Integer n) :% 1
334 fromEnum = fromInteger . truncate
336 enumFrom = numericEnumFrom
337 enumFromThen = numericEnumFromThen
338 enumFromTo = numericEnumFromTo
339 enumFromThenTo = numericEnumFromThenTo
343 %*********************************************************
345 \subsection{Coercions}
347 %*********************************************************
350 -- | general coercion from integral types
351 fromIntegral :: (Integral a, Num b) => a -> b
352 fromIntegral = fromInteger . toInteger
355 "fromIntegral/Int->Int" fromIntegral = id :: Int -> Int
358 -- | general coercion to fractional types
359 realToFrac :: (Real a, Fractional b) => a -> b
360 realToFrac = fromRational . toRational
363 "realToFrac/Int->Int" realToFrac = id :: Int -> Int
367 %*********************************************************
369 \subsection{Overloaded numeric functions}
371 %*********************************************************
374 -- | Converts a possibly-negative 'Real' value to a string.
375 showSigned :: (Real a)
376 => (a -> ShowS) -- ^ a function that can show unsigned values
377 -> Int -- ^ the precedence of the enclosing context
378 -> a -- ^ the value to show
380 showSigned showPos p x
381 | x < 0 = showParen (p > 6) (showChar '-' . showPos (-x))
382 | otherwise = showPos x
384 even, odd :: (Integral a) => a -> Bool
385 even n = n `rem` 2 == 0
388 -------------------------------------------------------
389 -- | raise a number to a non-negative integral power
390 {-# SPECIALISE (^) ::
391 Integer -> Integer -> Integer,
392 Integer -> Int -> Integer,
393 Int -> Int -> Int #-}
394 (^) :: (Num a, Integral b) => a -> b -> a
396 x ^ n | n > 0 = f x (n-1) x
398 f a d y = g a d where
399 g b i | even i = g (b*b) (i `quot` 2)
400 | otherwise = f b (i-1) (b*y)
401 _ ^ _ = error "Prelude.^: negative exponent"
403 -- | raise a number to an integral power
404 {-# SPECIALISE (^^) ::
405 Rational -> Int -> Rational #-}
406 (^^) :: (Fractional a, Integral b) => a -> b -> a
407 x ^^ n = if n >= 0 then x^n else recip (x^(negate n))
410 -------------------------------------------------------
411 -- | @'gcd' x y@ is the greatest (positive) integer that divides both @x@
412 -- and @y@; for example @'gcd' (-3) 6@ = @3@, @'gcd' (-3) (-6)@ = @3@,
413 -- @'gcd' 0 4@ = @4@. @'gcd' 0 0@ raises a runtime error.
414 gcd :: (Integral a) => a -> a -> a
415 gcd 0 0 = error "Prelude.gcd: gcd 0 0 is undefined"
416 gcd x y = gcd' (abs x) (abs y)
418 gcd' a b = gcd' b (a `rem` b)
420 -- | @'lcm' x y@ is the smallest positive integer that both @x@ and @y@ divide.
421 lcm :: (Integral a) => a -> a -> a
422 {-# SPECIALISE lcm :: Int -> Int -> Int #-}
425 lcm x y = abs ((x `quot` (gcd x y)) * y)
429 "gcd/Int->Int->Int" gcd = gcdInt
430 "gcd/Integer->Integer->Integer" gcd = gcdInteger
431 "lcm/Integer->Integer->Integer" lcm = lcmInteger
434 integralEnumFrom :: (Integral a, Bounded a) => a -> [a]
435 integralEnumFrom n = map fromInteger [toInteger n .. toInteger (maxBound `asTypeOf` n)]
437 integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a]
438 integralEnumFromThen n1 n2
439 | i_n2 >= i_n1 = map fromInteger [i_n1, i_n2 .. toInteger (maxBound `asTypeOf` n1)]
440 | otherwise = map fromInteger [i_n1, i_n2 .. toInteger (minBound `asTypeOf` n1)]
445 integralEnumFromTo :: Integral a => a -> a -> [a]
446 integralEnumFromTo n m = map fromInteger [toInteger n .. toInteger m]
448 integralEnumFromThenTo :: Integral a => a -> a -> a -> [a]
449 integralEnumFromThenTo n1 n2 m
450 = map fromInteger [toInteger n1, toInteger n2 .. toInteger m]