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