2 {-# OPTIONS -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 -----------------------------------------------------------------------------
20 import {-# SOURCE #-} GHC.Err
28 infixl 7 /, `quot`, `rem`, `div`, `mod`
31 default () -- Double isn't available yet,
32 -- and we shouldn't be using defaults anyway
36 %*********************************************************
38 \subsection{The @Ratio@ and @Rational@ types}
40 %*********************************************************
43 -- | Rational numbers, with numerator and denominator of some 'Integral' type.
44 data (Integral a) => Ratio a = !a :% !a deriving (Eq)
46 -- | Arbitrary-precision rational numbers, represented as a ratio of
47 -- two 'Integer' values. A rational number may be constructed using
49 type Rational = Ratio Integer
51 ratioPrec, ratioPrec1 :: Int
52 ratioPrec = 7 -- Precedence of ':%' constructor
53 ratioPrec1 = ratioPrec + 1
55 infinity, notANumber :: Rational
59 -- Use :%, not % for Inf/NaN; the latter would
60 -- immediately lead to a runtime error, because it normalises.
65 -- | Forms the ratio of two integral numbers.
66 {-# SPECIALISE (%) :: Integer -> Integer -> Rational #-}
67 (%) :: (Integral a) => a -> a -> Ratio a
69 -- | Extract the numerator of the ratio in reduced form:
70 -- the numerator and denominator have no common factor and the denominator
72 numerator :: (Integral a) => Ratio a -> a
74 -- | Extract the denominator of the ratio in reduced form:
75 -- the numerator and denominator have no common factor and the denominator
77 denominator :: (Integral a) => Ratio a -> a
80 \tr{reduce} is a subsidiary function used only in this module .
81 It normalises a ratio by dividing both numerator and denominator by
82 their greatest common divisor.
85 reduce :: (Integral a) => a -> a -> Ratio a
86 {-# SPECIALISE reduce :: Integer -> Integer -> Rational #-}
87 reduce _ 0 = error "Ratio.%: zero denominator"
88 reduce x y = (x `quot` d) :% (y `quot` d)
93 x % y = reduce (x * signum y) (abs y)
95 numerator (x :% _) = x
96 denominator (_ :% y) = y
100 %*********************************************************
102 \subsection{Standard numeric classes}
104 %*********************************************************
107 class (Num a, Ord a) => Real a where
108 -- | the rational equivalent of its real argument with full precision
109 toRational :: a -> Rational
111 -- | Integral numbers, supporting integer division.
113 -- Minimal complete definition: 'quotRem' and 'toInteger'
114 class (Real a, Enum a) => Integral a where
115 -- | integer division truncated toward zero
117 -- | integer remainder, satisfying
119 -- > (x `quot` y)*y + (x `rem` y) == x
121 -- | integer division truncated toward negative infinity
123 -- | integer modulus, satisfying
125 -- > (x `div` y)*y + (x `mod` y) == x
127 -- | simultaneous 'quot' and 'rem'
128 quotRem :: a -> a -> (a,a)
129 -- | simultaneous 'div' and 'mod'
130 divMod :: a -> a -> (a,a)
131 -- | conversion to 'Integer'
132 toInteger :: a -> Integer
134 n `quot` d = q where (q,_) = quotRem n d
135 n `rem` d = r where (_,r) = quotRem n d
136 n `div` d = q where (q,_) = divMod n d
137 n `mod` d = r where (_,r) = divMod n d
138 divMod n d = if signum r == negate (signum d) then (q-1, r+d) else qr
139 where qr@(q,r) = quotRem n d
141 -- | Fractional numbers, supporting real division.
143 -- Minimal complete definition: 'fromRational' and ('recip' or @('/')@)
144 class (Num a) => Fractional a where
145 -- | fractional division
147 -- | reciprocal fraction
149 -- | Conversion from a 'Rational' (that is @'Ratio' 'Integer'@).
150 -- A floating literal stands for an application of 'fromRational'
151 -- to a value of type 'Rational', so such literals have type
152 -- @('Fractional' a) => a@.
153 fromRational :: Rational -> a
158 -- | Extracting components of fractions.
160 -- Minimal complete definition: 'properFraction'
161 class (Real a, Fractional a) => RealFrac a where
162 -- | The function 'properFraction' takes a real fractional number @x@
163 -- and returns a pair @(n,f)@ such that @x = n+f@, and:
165 -- * @n@ is an integral number with the same sign as @x@; and
167 -- * @f@ is a fraction with the same type and sign as @x@,
168 -- and with absolute value less than @1@.
170 -- The default definitions of the 'ceiling', 'floor', 'truncate'
171 -- and 'round' functions are in terms of 'properFraction'.
172 properFraction :: (Integral b) => a -> (b,a)
173 -- | @'truncate' x@ returns the integer nearest @x@ between zero and @x@
174 truncate :: (Integral b) => a -> b
175 -- | @'round' x@ returns the nearest integer to @x@
176 round :: (Integral b) => a -> b
177 -- | @'ceiling' x@ returns the least integer not less than @x@
178 ceiling :: (Integral b) => a -> b
179 -- | @'floor' x@ returns the greatest integer not greater than @x@
180 floor :: (Integral b) => a -> b
182 truncate x = m where (m,_) = properFraction x
184 round x = let (n,r) = properFraction x
185 m = if r < 0 then n - 1 else n + 1
186 in case signum (abs r - 0.5) of
188 0 -> if even n then n else m
191 ceiling x = if r > 0 then n + 1 else n
192 where (n,r) = properFraction x
194 floor x = if r < 0 then n - 1 else n
195 where (n,r) = properFraction x
199 These 'numeric' enumerations come straight from the Report
202 numericEnumFrom :: (Fractional a) => a -> [a]
203 numericEnumFrom = iterate (+1)
205 numericEnumFromThen :: (Fractional a) => a -> a -> [a]
206 numericEnumFromThen n m = iterate (+(m-n)) n
208 numericEnumFromTo :: (Ord a, Fractional a) => a -> a -> [a]
209 numericEnumFromTo n m = takeWhile (<= m + 1/2) (numericEnumFrom n)
211 numericEnumFromThenTo :: (Ord a, Fractional a) => a -> a -> a -> [a]
212 numericEnumFromThenTo e1 e2 e3 = takeWhile pred (numericEnumFromThen e1 e2)
215 pred | e2 >= e1 = (<= e3 + mid)
216 | otherwise = (>= e3 + mid)
220 %*********************************************************
222 \subsection{Instances for @Int@}
224 %*********************************************************
227 instance Real Int where
228 toRational x = toInteger x % 1
230 instance Integral Int where
231 toInteger i = int2Integer i -- give back a full-blown Integer
233 a `quot` 0 = divZeroError
234 a `quot` b = a `quotInt` b
236 a `rem` 0 = divZeroError
237 a `rem` b = a `remInt` b
239 a `div` 0 = divZeroError
240 a `div` b = a `divInt` b
242 a `mod` 0 = divZeroError
243 a `mod` b = a `modInt` b
245 a `quotRem` 0 = divZeroError
246 a `quotRem` b = a `quotRemInt` b
248 a `divMod` 0 = divZeroError
249 a `divMod` b = a `divModInt` b
253 %*********************************************************
255 \subsection{Instances for @Integer@}
257 %*********************************************************
260 instance Real Integer where
263 instance Integral Integer where
266 a `quot` 0 = divZeroError
267 n `quot` d = n `quotInteger` d
269 a `rem` 0 = divZeroError
270 n `rem` d = n `remInteger` d
272 a `divMod` 0 = divZeroError
273 a `divMod` b = a `divModInteger` b
275 a `quotRem` 0 = divZeroError
276 a `quotRem` b = a `quotRemInteger` b
278 -- use the defaults for div & mod
282 %*********************************************************
284 \subsection{Instances for @Ratio@}
286 %*********************************************************
289 instance (Integral a) => Ord (Ratio a) where
290 {-# SPECIALIZE instance Ord Rational #-}
291 (x:%y) <= (x':%y') = x * y' <= x' * y
292 (x:%y) < (x':%y') = x * y' < x' * y
294 instance (Integral a) => Num (Ratio a) where
295 {-# SPECIALIZE instance Num Rational #-}
296 (x:%y) + (x':%y') = reduce (x*y' + x'*y) (y*y')
297 (x:%y) - (x':%y') = reduce (x*y' - x'*y) (y*y')
298 (x:%y) * (x':%y') = reduce (x * x') (y * y')
299 negate (x:%y) = (-x) :% y
300 abs (x:%y) = abs x :% y
301 signum (x:%_) = signum x :% 1
302 fromInteger x = fromInteger x :% 1
304 instance (Integral a) => Fractional (Ratio a) where
305 {-# SPECIALIZE instance Fractional Rational #-}
306 (x:%y) / (x':%y') = (x*y') % (y*x')
308 fromRational (x:%y) = fromInteger x :% fromInteger y
310 instance (Integral a) => Real (Ratio a) where
311 {-# SPECIALIZE instance Real Rational #-}
312 toRational (x:%y) = toInteger x :% toInteger y
314 instance (Integral a) => RealFrac (Ratio a) where
315 {-# SPECIALIZE instance RealFrac Rational #-}
316 properFraction (x:%y) = (fromInteger (toInteger q), r:%y)
317 where (q,r) = quotRem x y
319 instance (Integral a) => Show (Ratio a) where
320 {-# SPECIALIZE instance Show Rational #-}
321 showsPrec p (x:%y) = showParen (p > ratioPrec) $
322 showsPrec ratioPrec1 x .
323 showString "%" . -- H98 report has spaces round the %
324 -- but we removed them [May 04]
325 showsPrec ratioPrec1 y
327 instance (Integral a) => Enum (Ratio a) where
328 {-# SPECIALIZE instance Enum Rational #-}
332 toEnum n = fromInteger (int2Integer n) :% 1
333 fromEnum = fromInteger . truncate
335 enumFrom = numericEnumFrom
336 enumFromThen = numericEnumFromThen
337 enumFromTo = numericEnumFromTo
338 enumFromThenTo = numericEnumFromThenTo
342 %*********************************************************
344 \subsection{Coercions}
346 %*********************************************************
349 -- | general coercion from integral types
350 fromIntegral :: (Integral a, Num b) => a -> b
351 fromIntegral = fromInteger . toInteger
354 "fromIntegral/Int->Int" fromIntegral = id :: Int -> Int
357 -- | general coercion to fractional types
358 realToFrac :: (Real a, Fractional b) => a -> b
359 realToFrac = fromRational . toRational
362 "realToFrac/Int->Int" realToFrac = id :: Int -> Int
366 %*********************************************************
368 \subsection{Overloaded numeric functions}
370 %*********************************************************
373 -- | Converts a possibly-negative 'Real' value to a string.
374 showSigned :: (Real a)
375 => (a -> ShowS) -- ^ a function that can show unsigned values
376 -> Int -- ^ the precedence of the enclosing context
377 -> a -- ^ the value to show
379 showSigned showPos p x
380 | x < 0 = showParen (p > 6) (showChar '-' . showPos (-x))
381 | otherwise = showPos x
383 even, odd :: (Integral a) => a -> Bool
384 even n = n `rem` 2 == 0
387 -------------------------------------------------------
388 -- | raise a number to a non-negative integral power
389 {-# SPECIALISE (^) ::
390 Integer -> Integer -> Integer,
391 Integer -> Int -> Integer,
392 Int -> Int -> Int #-}
393 (^) :: (Num a, Integral b) => a -> b -> a
395 x ^ n | n > 0 = f x (n-1) x
397 f a d y = g a d where
398 g b i | even i = g (b*b) (i `quot` 2)
399 | otherwise = f b (i-1) (b*y)
400 _ ^ _ = error "Prelude.^: negative exponent"
402 -- | raise a number to an integral power
403 {-# SPECIALISE (^^) ::
404 Rational -> Int -> Rational #-}
405 (^^) :: (Fractional a, Integral b) => a -> b -> a
406 x ^^ n = if n >= 0 then x^n else recip (x^(negate n))
409 -------------------------------------------------------
410 -- | @'gcd' x y@ is the greatest (positive) integer that divides both @x@
411 -- and @y@; for example @'gcd' (-3) 6@ = @3@, @'gcd' (-3) (-6)@ = @3@,
412 -- @'gcd' 0 4@ = @4@. @'gcd' 0 0@ raises a runtime error.
413 gcd :: (Integral a) => a -> a -> a
414 gcd 0 0 = error "Prelude.gcd: gcd 0 0 is undefined"
415 gcd x y = gcd' (abs x) (abs y)
417 gcd' a b = gcd' b (a `rem` b)
419 -- | @'lcm' x y@ is the smallest positive integer that both @x@ and @y@ divide.
420 lcm :: (Integral a) => a -> a -> a
421 {-# SPECIALISE lcm :: Int -> Int -> Int #-}
424 lcm x y = abs ((x `quot` (gcd x y)) * y)
428 "gcd/Int->Int->Int" gcd = gcdInt
429 "gcd/Integer->Integer->Integer" gcd = gcdInteger
430 "lcm/Integer->Integer->Integer" lcm = lcmInteger
433 integralEnumFrom :: (Integral a, Bounded a) => a -> [a]
434 integralEnumFrom n = map fromInteger [toInteger n .. toInteger (maxBound `asTypeOf` n)]
436 integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a]
437 integralEnumFromThen n1 n2
438 | i_n2 >= i_n1 = map fromInteger [i_n1, i_n2 .. toInteger (maxBound `asTypeOf` n1)]
439 | otherwise = map fromInteger [i_n1, i_n2 .. toInteger (minBound `asTypeOf` n1)]
444 integralEnumFromTo :: Integral a => a -> a -> [a]
445 integralEnumFromTo n m = map fromInteger [toInteger n .. toInteger m]
447 integralEnumFromThenTo :: Integral a => a -> a -> a -> [a]
448 integralEnumFromThenTo n1 n2 m
449 = map fromInteger [toInteger n1, toInteger n2 .. toInteger m]