Update the exitWith docs
[ghc-base.git] / GHC / Real.lhs
1 \begin{code}
2 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
3 {-# OPTIONS_HADDOCK hide #-}
4 -----------------------------------------------------------------------------
5 -- |
6 -- Module      :  GHC.Real
7 -- Copyright   :  (c) The University of Glasgow, 1994-2002
8 -- License     :  see libraries/base/LICENSE
9 -- 
10 -- Maintainer  :  cvs-ghc@haskell.org
11 -- Stability   :  internal
12 -- Portability :  non-portable (GHC Extensions)
13 --
14 -- The types 'Ratio' and 'Rational', and the classes 'Real', 'Fractional',
15 -- 'Integral', and 'RealFrac'.
16 --
17 -----------------------------------------------------------------------------
18
19 -- #hide
20 module GHC.Real where
21
22 import GHC.Base
23 import GHC.Num
24 import GHC.List
25 import GHC.Enum
26 import GHC.Show
27 import GHC.Err
28
29 infixr 8  ^, ^^
30 infixl 7  /, `quot`, `rem`, `div`, `mod`
31 infixl 7  %
32
33 default ()              -- Double isn't available yet, 
34                         -- and we shouldn't be using defaults anyway
35 \end{code}
36
37
38 %*********************************************************
39 %*                                                      *
40 \subsection{The @Ratio@ and @Rational@ types}
41 %*                                                      *
42 %*********************************************************
43
44 \begin{code}
45 -- | Rational numbers, with numerator and denominator of some 'Integral' type.
46 data  (Integral a)      => Ratio a = !a :% !a  deriving (Eq)
47
48 -- | Arbitrary-precision rational numbers, represented as a ratio of
49 -- two 'Integer' values.  A rational number may be constructed using
50 -- the '%' operator.
51 type  Rational          =  Ratio Integer
52
53 ratioPrec, ratioPrec1 :: Int
54 ratioPrec  = 7  -- Precedence of ':%' constructor
55 ratioPrec1 = ratioPrec + 1
56
57 infinity, notANumber, negativeZero :: Rational
58 infinity   = 1 :% 0
59 notANumber = 0 :% 0
60 negativeZero = 0 :% (-1)
61
62 -- Use :%, not % for Inf/NaN; the latter would 
63 -- immediately lead to a runtime error, because it normalises. 
64 \end{code}
65
66
67 \begin{code}
68 -- | Forms the ratio of two integral numbers.
69 {-# SPECIALISE (%) :: Integer -> Integer -> Rational #-}
70 (%)                     :: (Integral a) => a -> a -> Ratio a
71
72 -- | Extract the numerator of the ratio in reduced form:
73 -- the numerator and denominator have no common factor and the denominator
74 -- is positive.
75 numerator       :: (Integral a) => Ratio a -> a
76
77 -- | Extract the denominator of the ratio in reduced form:
78 -- the numerator and denominator have no common factor and the denominator
79 -- is positive.
80 denominator     :: (Integral a) => Ratio a -> a
81 \end{code}
82
83 \tr{reduce} is a subsidiary function used only in this module .
84 It normalises a ratio by dividing both numerator and denominator by
85 their greatest common divisor.
86
87 \begin{code}
88 reduce ::  (Integral a) => a -> a -> Ratio a
89 {-# SPECIALISE reduce :: Integer -> Integer -> Rational #-}
90 reduce _ 0              =  error "Ratio.%: zero denominator"
91 reduce x y              =  (x `quot` d) :% (y `quot` d)
92                            where d = gcd x y
93 \end{code}
94
95 \begin{code}
96 x % y                   =  reduce (x * signum y) (abs y)
97
98 numerator   (x :% _)    =  x
99 denominator (_ :% y)    =  y
100 \end{code}
101
102
103 %*********************************************************
104 %*                                                      *
105 \subsection{Standard numeric classes}
106 %*                                                      *
107 %*********************************************************
108
109 \begin{code}
110 class  (Num a, Ord a) => Real a  where
111     -- | the rational equivalent of its real argument with full precision
112     toRational          ::  a -> Rational
113
114 -- | Integral numbers, supporting integer division.
115 --
116 -- Minimal complete definition: 'quotRem' and 'toInteger'
117 class  (Real a, Enum a) => Integral a  where
118     -- | integer division truncated toward zero
119     quot                :: a -> a -> a
120     -- | integer remainder, satisfying
121     --
122     -- > (x `quot` y)*y + (x `rem` y) == x
123     rem                 :: a -> a -> a
124     -- | integer division truncated toward negative infinity
125     div                 :: a -> a -> a
126     -- | integer modulus, satisfying
127     --
128     -- > (x `div` y)*y + (x `mod` y) == x
129     mod                 :: a -> a -> a
130     -- | simultaneous 'quot' and 'rem'
131     quotRem             :: a -> a -> (a,a)
132     -- | simultaneous 'div' and 'mod'
133     divMod              :: a -> a -> (a,a)
134     -- | conversion to 'Integer'
135     toInteger           :: a -> Integer
136
137     {-# INLINE quot #-}
138     {-# INLINE rem #-}
139     {-# INLINE div #-}
140     {-# INLINE mod #-}
141     n `quot` d          =  q  where (q,_) = quotRem n d
142     n `rem` d           =  r  where (_,r) = quotRem n d
143     n `div` d           =  q  where (q,_) = divMod n d
144     n `mod` d           =  r  where (_,r) = divMod n d
145
146     divMod n d          =  if signum r == negate (signum d) then (q-1, r+d) else qr
147                            where qr@(q,r) = quotRem n d
148
149 -- | Fractional numbers, supporting real division.
150 --
151 -- Minimal complete definition: 'fromRational' and ('recip' or @('/')@)
152 class  (Num a) => Fractional a  where
153     -- | fractional division
154     (/)                 :: a -> a -> a
155     -- | reciprocal fraction
156     recip               :: a -> a
157     -- | Conversion from a 'Rational' (that is @'Ratio' 'Integer'@).
158     -- A floating literal stands for an application of 'fromRational'
159     -- to a value of type 'Rational', so such literals have type
160     -- @('Fractional' a) => a@.
161     fromRational        :: Rational -> a
162
163     {-# INLINE recip #-}
164     {-# INLINE (/) #-}
165     recip x             =  1 / x
166     x / y               = x * recip y
167
168 -- | Extracting components of fractions.
169 --
170 -- Minimal complete definition: 'properFraction'
171 class  (Real a, Fractional a) => RealFrac a  where
172     -- | The function 'properFraction' takes a real fractional number @x@
173     -- and returns a pair @(n,f)@ such that @x = n+f@, and:
174     --
175     -- * @n@ is an integral number with the same sign as @x@; and
176     --
177     -- * @f@ is a fraction with the same type and sign as @x@,
178     --   and with absolute value less than @1@.
179     --
180     -- The default definitions of the 'ceiling', 'floor', 'truncate'
181     -- and 'round' functions are in terms of 'properFraction'.
182     properFraction      :: (Integral b) => a -> (b,a)
183     -- | @'truncate' x@ returns the integer nearest @x@ between zero and @x@
184     truncate            :: (Integral b) => a -> b
185     -- | @'round' x@ returns the nearest integer to @x@;
186     --   the even integer if @x@ is equidistant between two integers
187     round               :: (Integral b) => a -> b
188     -- | @'ceiling' x@ returns the least integer not less than @x@
189     ceiling             :: (Integral b) => a -> b
190     -- | @'floor' x@ returns the greatest integer not greater than @x@
191     floor               :: (Integral b) => a -> b
192
193     {-# INLINE truncate #-}
194     truncate x          =  m  where (m,_) = properFraction x
195     
196     round x             =  let (n,r) = properFraction x
197                                m     = if r < 0 then n - 1 else n + 1
198                            in case signum (abs r - 0.5) of
199                                 -1 -> n
200                                 0  -> if even n then n else m
201                                 1  -> m
202                                 _  -> error "round default defn: Bad value"
203     
204     ceiling x           =  if r > 0 then n + 1 else n
205                            where (n,r) = properFraction x
206     
207     floor x             =  if r < 0 then n - 1 else n
208                            where (n,r) = properFraction x
209 \end{code}
210
211
212 These 'numeric' enumerations come straight from the Report
213
214 \begin{code}
215 numericEnumFrom         :: (Fractional a) => a -> [a]
216 numericEnumFrom n       =  n `seq` (n : numericEnumFrom (n + 1))
217
218 numericEnumFromThen     :: (Fractional a) => a -> a -> [a]
219 numericEnumFromThen n m = n `seq` m `seq` (n : numericEnumFromThen m (m+m-n))
220
221 numericEnumFromTo       :: (Ord a, Fractional a) => a -> a -> [a]
222 numericEnumFromTo n m   = takeWhile (<= m + 1/2) (numericEnumFrom n)
223
224 numericEnumFromThenTo   :: (Ord a, Fractional a) => a -> a -> a -> [a]
225 numericEnumFromThenTo e1 e2 e3
226     = takeWhile predicate (numericEnumFromThen e1 e2)
227                                 where
228                                  mid = (e2 - e1) / 2
229                                  predicate | e2 >= e1  = (<= e3 + mid)
230                                            | otherwise = (>= e3 + mid)
231 \end{code}
232
233
234 %*********************************************************
235 %*                                                      *
236 \subsection{Instances for @Int@}
237 %*                                                      *
238 %*********************************************************
239
240 \begin{code}
241 instance  Real Int  where
242     toRational x        =  toInteger x % 1
243
244 instance  Integral Int  where
245     toInteger (I# i) = smallInteger i
246
247     a `quot` b
248      | b == 0                     = divZeroError
249      | a == minBound && b == (-1) = overflowError
250      | otherwise                  =  a `quotInt` b
251
252     a `rem` b
253      | b == 0                     = divZeroError
254      | a == minBound && b == (-1) = overflowError
255      | otherwise                  =  a `remInt` b
256
257     a `div` b
258      | b == 0                     = divZeroError
259      | a == minBound && b == (-1) = overflowError
260      | otherwise                  =  a `divInt` b
261
262     a `mod` b
263      | b == 0                     = divZeroError
264      | a == minBound && b == (-1) = overflowError
265      | otherwise                  =  a `modInt` b
266
267     a `quotRem` b
268      | b == 0                     = divZeroError
269      | a == minBound && b == (-1) = overflowError
270      | otherwise                  =  a `quotRemInt` b
271
272     a `divMod` b
273      | b == 0                     = divZeroError
274      | a == minBound && b == (-1) = overflowError
275      | otherwise                  =  a `divModInt` b
276 \end{code}
277
278
279 %*********************************************************
280 %*                                                      *
281 \subsection{Instances for @Integer@}
282 %*                                                      *
283 %*********************************************************
284
285 \begin{code}
286 instance  Real Integer  where
287     toRational x        =  x % 1
288
289 instance  Integral Integer where
290     toInteger n      = n
291
292     _ `quot` 0 = divZeroError
293     n `quot` d = n `quotInteger` d
294
295     _ `rem` 0 = divZeroError
296     n `rem`  d = n `remInteger`  d
297
298     _ `divMod` 0 = divZeroError
299     a `divMod` b = case a `divModInteger` b of
300                    (# x, y #) -> (x, y)
301
302     _ `quotRem` 0 = divZeroError
303     a `quotRem` b = case a `quotRemInteger` b of
304                     (# q, r #) -> (q, r)
305
306     -- use the defaults for div & mod
307 \end{code}
308
309
310 %*********************************************************
311 %*                                                      *
312 \subsection{Instances for @Ratio@}
313 %*                                                      *
314 %*********************************************************
315
316 \begin{code}
317 instance  (Integral a)  => Ord (Ratio a)  where
318     {-# SPECIALIZE instance Ord Rational #-}
319     (x:%y) <= (x':%y')  =  x * y' <= x' * y
320     (x:%y) <  (x':%y')  =  x * y' <  x' * y
321
322 instance  (Integral a)  => Num (Ratio a)  where
323     {-# SPECIALIZE instance Num Rational #-}
324     (x:%y) + (x':%y')   =  reduce (x*y' + x'*y) (y*y')
325     (x:%y) - (x':%y')   =  reduce (x*y' - x'*y) (y*y')
326     (x:%y) * (x':%y')   =  reduce (x * x') (y * y')
327     negate (x:%y)       =  (-x) :% y
328     abs (x:%y)          =  abs x :% y
329     signum (x:%_)       =  signum x :% 1
330     fromInteger x       =  fromInteger x :% 1
331
332 instance  (Integral a)  => Fractional (Ratio a)  where
333     {-# SPECIALIZE instance Fractional Rational #-}
334     (x:%y) / (x':%y')   =  (x*y') % (y*x')
335     recip (x:%y)        =  y % x
336     fromRational (x:%y) =  fromInteger x :% fromInteger y
337
338 instance  (Integral a)  => Real (Ratio a)  where
339     {-# SPECIALIZE instance Real Rational #-}
340     toRational (x:%y)   =  toInteger x :% toInteger y
341
342 instance  (Integral a)  => RealFrac (Ratio a)  where
343     {-# SPECIALIZE instance RealFrac Rational #-}
344     properFraction (x:%y) = (fromInteger (toInteger q), r:%y)
345                           where (q,r) = quotRem x y
346
347 instance  (Integral a)  => Show (Ratio a)  where
348     {-# SPECIALIZE instance Show Rational #-}
349     showsPrec p (x:%y)  =  showParen (p > ratioPrec) $
350                            showsPrec ratioPrec1 x . 
351                            showString " % " .
352                            -- H98 report has spaces round the %
353                            -- but we removed them [May 04]
354                            -- and added them again for consistency with
355                            -- Haskell 98 [Sep 08, #1920]
356                            showsPrec ratioPrec1 y
357
358 instance  (Integral a)  => Enum (Ratio a)  where
359     {-# SPECIALIZE instance Enum Rational #-}
360     succ x              =  x + 1
361     pred x              =  x - 1
362
363     toEnum n            =  fromIntegral n :% 1
364     fromEnum            =  fromInteger . truncate
365
366     enumFrom            =  numericEnumFrom
367     enumFromThen        =  numericEnumFromThen
368     enumFromTo          =  numericEnumFromTo
369     enumFromThenTo      =  numericEnumFromThenTo
370 \end{code}
371
372
373 %*********************************************************
374 %*                                                      *
375 \subsection{Coercions}
376 %*                                                      *
377 %*********************************************************
378
379 \begin{code}
380 -- | general coercion from integral types
381 fromIntegral :: (Integral a, Num b) => a -> b
382 fromIntegral = fromInteger . toInteger
383
384 {-# RULES
385 "fromIntegral/Int->Int" fromIntegral = id :: Int -> Int
386     #-}
387
388 -- | general coercion to fractional types
389 realToFrac :: (Real a, Fractional b) => a -> b
390 realToFrac = fromRational . toRational
391
392 {-# RULES
393 "realToFrac/Int->Int" realToFrac = id :: Int -> Int
394     #-}
395 \end{code}
396
397 %*********************************************************
398 %*                                                      *
399 \subsection{Overloaded numeric functions}
400 %*                                                      *
401 %*********************************************************
402
403 \begin{code}
404 -- | Converts a possibly-negative 'Real' value to a string.
405 showSigned :: (Real a)
406   => (a -> ShowS)       -- ^ a function that can show unsigned values
407   -> Int                -- ^ the precedence of the enclosing context
408   -> a                  -- ^ the value to show
409   -> ShowS
410 showSigned showPos p x 
411    | x < 0     = showParen (p > 6) (showChar '-' . showPos (-x))
412    | otherwise = showPos x
413
414 even, odd       :: (Integral a) => a -> Bool
415 even n          =  n `rem` 2 == 0
416 odd             =  not . even
417
418 -------------------------------------------------------
419 -- | raise a number to a non-negative integral power
420 {-# SPECIALISE (^) ::
421         Integer -> Integer -> Integer,
422         Integer -> Int -> Integer,
423         Int -> Int -> Int #-}
424 (^) :: (Num a, Integral b) => a -> b -> a
425 x0 ^ y0 | y0 < 0    = error "Negative exponent"
426         | y0 == 0   = 1
427         | otherwise = f x0 y0
428     where -- f : x0 ^ y0 = x ^ y
429           f x y | even y    = f (x * x) (y `quot` 2)
430                 | y == 1    = x
431                 | otherwise = g (x * x) ((y - 1) `quot` 2) x
432           -- g : x0 ^ y0 = (x ^ y) * z
433           g x y z | even y = g (x * x) (y `quot` 2) z
434                   | y == 1 = x * z
435                   | otherwise = g (x * x) ((y - 1) `quot` 2) (x * z)
436
437 -- | raise a number to an integral power
438 {-# SPECIALISE (^^) ::
439         Rational -> Int -> Rational #-}
440 (^^)            :: (Fractional a, Integral b) => a -> b -> a
441 x ^^ n          =  if n >= 0 then x^n else recip (x^(negate n))
442
443
444 -------------------------------------------------------
445 -- | @'gcd' x y@ is the greatest (positive) integer that divides both @x@
446 -- and @y@; for example @'gcd' (-3) 6@ = @3@, @'gcd' (-3) (-6)@ = @3@,
447 -- @'gcd' 0 4@ = @4@.  @'gcd' 0 0@ raises a runtime error.
448 gcd             :: (Integral a) => a -> a -> a
449 gcd 0 0         =  error "Prelude.gcd: gcd 0 0 is undefined"
450 gcd x y         =  gcd' (abs x) (abs y)
451                    where gcd' a 0  =  a
452                          gcd' a b  =  gcd' b (a `rem` b)
453
454 -- | @'lcm' x y@ is the smallest positive integer that both @x@ and @y@ divide.
455 lcm             :: (Integral a) => a -> a -> a
456 {-# SPECIALISE lcm :: Int -> Int -> Int #-}
457 lcm _ 0         =  0
458 lcm 0 _         =  0
459 lcm x y         =  abs ((x `quot` (gcd x y)) * y)
460
461 #ifdef OPTIMISE_INTEGER_GCD_LCM
462 {-# RULES
463 "gcd/Int->Int->Int"             gcd = gcdInt
464 "gcd/Integer->Integer->Integer" gcd = gcdInteger'
465 "lcm/Integer->Integer->Integer" lcm = lcmInteger
466  #-}
467
468 gcdInteger' :: Integer -> Integer -> Integer
469 gcdInteger' 0 0 = error "GHC.Real.gcdInteger': gcd 0 0 is undefined"
470 gcdInteger' a b = gcdInteger a b
471
472 gcdInt :: Int -> Int -> Int
473 gcdInt 0 0 = error "GHC.Real.gcdInt: gcd 0 0 is undefined"
474 gcdInt a b = fromIntegral (gcdInteger (fromIntegral a) (fromIntegral b))
475 #endif
476
477 integralEnumFrom :: (Integral a, Bounded a) => a -> [a]
478 integralEnumFrom n = map fromInteger [toInteger n .. toInteger (maxBound `asTypeOf` n)]
479
480 integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a]
481 integralEnumFromThen n1 n2
482   | i_n2 >= i_n1  = map fromInteger [i_n1, i_n2 .. toInteger (maxBound `asTypeOf` n1)]
483   | otherwise     = map fromInteger [i_n1, i_n2 .. toInteger (minBound `asTypeOf` n1)]
484   where
485     i_n1 = toInteger n1
486     i_n2 = toInteger n2
487
488 integralEnumFromTo :: Integral a => a -> a -> [a]
489 integralEnumFromTo n m = map fromInteger [toInteger n .. toInteger m]
490
491 integralEnumFromThenTo :: Integral a => a -> a -> a -> [a]
492 integralEnumFromThenTo n1 n2 m
493   = map fromInteger [toInteger n1, toInteger n2 .. toInteger m]
494 \end{code}