17d04526ee0fc87abd546cdd9e10378dc1401b7b
[ghc-base.git] / GHC / Real.lhs
1 \begin{code}
2 {-# LANGUAGE CPP, NoImplicitPrelude, MagicHash, UnboxedTuples #-}
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 :: Rational
58 infinity   = 1 :% 0
59 notANumber = 0 :% 0
60
61 -- Use :%, not % for Inf/NaN; the latter would
62 -- immediately lead to a runtime error, because it normalises.
63 \end{code}
64
65
66 \begin{code}
67 -- | Forms the ratio of two integral numbers.
68 {-# SPECIALISE (%) :: Integer -> Integer -> Rational #-}
69 (%)                     :: (Integral a) => a -> a -> Ratio a
70
71 -- | Extract the numerator of the ratio in reduced form:
72 -- the numerator and denominator have no common factor and the denominator
73 -- is positive.
74 numerator       :: (Integral a) => Ratio a -> a
75
76 -- | Extract the denominator of the ratio in reduced form:
77 -- the numerator and denominator have no common factor and the denominator
78 -- is positive.
79 denominator     :: (Integral a) => Ratio a -> a
80 \end{code}
81
82 \tr{reduce} is a subsidiary function used only in this module .
83 It normalises a ratio by dividing both numerator and denominator by
84 their greatest common divisor.
85
86 \begin{code}
87 reduce ::  (Integral a) => a -> a -> Ratio a
88 {-# SPECIALISE reduce :: Integer -> Integer -> Rational #-}
89 reduce _ 0              =  error "Ratio.%: zero denominator"
90 reduce x y              =  (x `quot` d) :% (y `quot` d)
91                            where d = gcd x y
92 \end{code}
93
94 \begin{code}
95 x % y                   =  reduce (x * signum y) (abs y)
96
97 numerator   (x :% _)    =  x
98 denominator (_ :% y)    =  y
99 \end{code}
100
101
102 %*********************************************************
103 %*                                                      *
104 \subsection{Standard numeric classes}
105 %*                                                      *
106 %*********************************************************
107
108 \begin{code}
109 class  (Num a, Ord a) => Real a  where
110     -- | the rational equivalent of its real argument with full precision
111     toRational          ::  a -> Rational
112
113 -- | Integral numbers, supporting integer division.
114 --
115 -- Minimal complete definition: 'quotRem' and 'toInteger'
116 class  (Real a, Enum a) => Integral a  where
117     -- | integer division truncated toward zero
118     quot                :: a -> a -> a
119     -- | integer remainder, satisfying
120     --
121     -- > (x `quot` y)*y + (x `rem` y) == x
122     rem                 :: a -> a -> a
123     -- | integer division truncated toward negative infinity
124     div                 :: a -> a -> a
125     -- | integer modulus, satisfying
126     --
127     -- > (x `div` y)*y + (x `mod` y) == x
128     mod                 :: a -> a -> a
129     -- | simultaneous 'quot' and 'rem'
130     quotRem             :: a -> a -> (a,a)
131     -- | simultaneous 'div' and 'mod'
132     divMod              :: a -> a -> (a,a)
133     -- | conversion to 'Integer'
134     toInteger           :: a -> Integer
135
136     {-# INLINE quot #-}
137     {-# INLINE rem #-}
138     {-# INLINE div #-}
139     {-# INLINE mod #-}
140     n `quot` d          =  q  where (q,_) = quotRem n d
141     n `rem` d           =  r  where (_,r) = quotRem n d
142     n `div` d           =  q  where (q,_) = divMod n d
143     n `mod` d           =  r  where (_,r) = divMod n d
144
145     divMod n d          =  if signum r == negate (signum d) then (q-1, r+d) else qr
146                            where qr@(q,r) = quotRem n d
147
148 -- | Fractional numbers, supporting real division.
149 --
150 -- Minimal complete definition: 'fromRational' and ('recip' or @('/')@)
151 class  (Num a) => Fractional a  where
152     -- | fractional division
153     (/)                 :: a -> a -> a
154     -- | reciprocal fraction
155     recip               :: a -> a
156     -- | Conversion from a 'Rational' (that is @'Ratio' 'Integer'@).
157     -- A floating literal stands for an application of 'fromRational'
158     -- to a value of type 'Rational', so such literals have type
159     -- @('Fractional' a) => a@.
160     fromRational        :: Rational -> a
161
162     {-# INLINE recip #-}
163     {-# INLINE (/) #-}
164     recip x             =  1 / x
165     x / y               = x * recip y
166
167 -- | Extracting components of fractions.
168 --
169 -- Minimal complete definition: 'properFraction'
170 class  (Real a, Fractional a) => RealFrac a  where
171     -- | The function 'properFraction' takes a real fractional number @x@
172     -- and returns a pair @(n,f)@ such that @x = n+f@, and:
173     --
174     -- * @n@ is an integral number with the same sign as @x@; and
175     --
176     -- * @f@ is a fraction with the same type and sign as @x@,
177     --   and with absolute value less than @1@.
178     --
179     -- The default definitions of the 'ceiling', 'floor', 'truncate'
180     -- and 'round' functions are in terms of 'properFraction'.
181     properFraction      :: (Integral b) => a -> (b,a)
182     -- | @'truncate' x@ returns the integer nearest @x@ between zero and @x@
183     truncate            :: (Integral b) => a -> b
184     -- | @'round' x@ returns the nearest integer to @x@;
185     --   the even integer if @x@ is equidistant between two integers
186     round               :: (Integral b) => a -> b
187     -- | @'ceiling' x@ returns the least integer not less than @x@
188     ceiling             :: (Integral b) => a -> b
189     -- | @'floor' x@ returns the greatest integer not greater than @x@
190     floor               :: (Integral b) => a -> b
191
192     {-# INLINE truncate #-}
193     truncate x          =  m  where (m,_) = properFraction x
194
195     round x             =  let (n,r) = properFraction x
196                                m     = if r < 0 then n - 1 else n + 1
197                            in case signum (abs r - 0.5) of
198                                 -1 -> n
199                                 0  -> if even n then n else m
200                                 1  -> m
201                                 _  -> error "round default defn: Bad value"
202
203     ceiling x           =  if r > 0 then n + 1 else n
204                            where (n,r) = properFraction x
205
206     floor x             =  if r < 0 then n - 1 else n
207                            where (n,r) = properFraction x
208 \end{code}
209
210
211 These 'numeric' enumerations come straight from the Report
212
213 \begin{code}
214 numericEnumFrom         :: (Fractional a) => a -> [a]
215 numericEnumFrom n       =  n `seq` (n : numericEnumFrom (n + 1))
216
217 numericEnumFromThen     :: (Fractional a) => a -> a -> [a]
218 numericEnumFromThen n m = n `seq` m `seq` (n : numericEnumFromThen m (m+m-n))
219
220 numericEnumFromTo       :: (Ord a, Fractional a) => a -> a -> [a]
221 numericEnumFromTo n m   = takeWhile (<= m + 1/2) (numericEnumFrom n)
222
223 numericEnumFromThenTo   :: (Ord a, Fractional a) => a -> a -> a -> [a]
224 numericEnumFromThenTo e1 e2 e3
225     = takeWhile predicate (numericEnumFromThen e1 e2)
226                                 where
227                                  mid = (e2 - e1) / 2
228                                  predicate | e2 >= e1  = (<= e3 + mid)
229                                            | otherwise = (>= e3 + mid)
230 \end{code}
231
232
233 %*********************************************************
234 %*                                                      *
235 \subsection{Instances for @Int@}
236 %*                                                      *
237 %*********************************************************
238
239 \begin{code}
240 instance  Real Int  where
241     toRational x        =  toInteger x % 1
242
243 instance  Integral Int  where
244     toInteger (I# i) = smallInteger i
245
246     a `quot` b
247      | b == 0                     = divZeroError
248      | b == (-1) && a == minBound = overflowError -- Note [Order of tests]
249                                                   -- in GHC.Int
250      | otherwise                  =  a `quotInt` b
251
252     a `rem` b
253      | b == 0                     = divZeroError
254      | b == (-1) && a == minBound = overflowError -- Note [Order of tests]
255                                                   -- in GHC.Int
256      | otherwise                  =  a `remInt` b
257
258     a `div` b
259      | b == 0                     = divZeroError
260      | b == (-1) && a == minBound = overflowError -- Note [Order of tests]
261                                                   -- in GHC.Int
262      | otherwise                  =  a `divInt` b
263
264     a `mod` b
265      | b == 0                     = divZeroError
266      | b == (-1) && a == minBound = overflowError -- Note [Order of tests]
267                                                   -- in GHC.Int
268      | otherwise                  =  a `modInt` b
269
270     a `quotRem` b
271      | b == 0                     = divZeroError
272      | b == (-1) && a == minBound = overflowError -- Note [Order of tests]
273                                                   -- in GHC.Int
274      | otherwise                  =  a `quotRemInt` b
275
276     a `divMod` b
277      | b == 0                     = divZeroError
278      | b == (-1) && a == minBound = overflowError -- Note [Order of tests]
279                                                   -- in GHC.Int
280      | otherwise                  =  a `divModInt` b
281 \end{code}
282
283
284 %*********************************************************
285 %*                                                      *
286 \subsection{Instances for @Integer@}
287 %*                                                      *
288 %*********************************************************
289
290 \begin{code}
291 instance  Real Integer  where
292     toRational x        =  x % 1
293
294 instance  Integral Integer where
295     toInteger n      = n
296
297     _ `quot` 0 = divZeroError
298     n `quot` d = n `quotInteger` d
299
300     _ `rem` 0 = divZeroError
301     n `rem`  d = n `remInteger`  d
302
303     _ `divMod` 0 = divZeroError
304     a `divMod` b = case a `divModInteger` b of
305                    (# x, y #) -> (x, y)
306
307     _ `quotRem` 0 = divZeroError
308     a `quotRem` b = case a `quotRemInteger` b of
309                     (# q, r #) -> (q, r)
310
311     -- use the defaults for div & mod
312 \end{code}
313
314
315 %*********************************************************
316 %*                                                      *
317 \subsection{Instances for @Ratio@}
318 %*                                                      *
319 %*********************************************************
320
321 \begin{code}
322 instance  (Integral a)  => Ord (Ratio a)  where
323     {-# SPECIALIZE instance Ord Rational #-}
324     (x:%y) <= (x':%y')  =  x * y' <= x' * y
325     (x:%y) <  (x':%y')  =  x * y' <  x' * y
326
327 instance  (Integral a)  => Num (Ratio a)  where
328     {-# SPECIALIZE instance Num Rational #-}
329     (x:%y) + (x':%y')   =  reduce (x*y' + x'*y) (y*y')
330     (x:%y) - (x':%y')   =  reduce (x*y' - x'*y) (y*y')
331     (x:%y) * (x':%y')   =  reduce (x * x') (y * y')
332     negate (x:%y)       =  (-x) :% y
333     abs (x:%y)          =  abs x :% y
334     signum (x:%_)       =  signum x :% 1
335     fromInteger x       =  fromInteger x :% 1
336
337 {-# RULES "fromRational/id" fromRational = id :: Rational -> Rational #-}
338 instance  (Integral a)  => Fractional (Ratio a)  where
339     {-# SPECIALIZE instance Fractional Rational #-}
340     (x:%y) / (x':%y')   =  (x*y') % (y*x')
341     recip (0:%_)        = error "Ratio.%: zero denominator"
342     recip (x:%y)
343         | x < 0         = negate y :% negate x
344         | otherwise     = y :% x
345     fromRational (x:%y) =  fromInteger x % fromInteger y
346
347 instance  (Integral a)  => Real (Ratio a)  where
348     {-# SPECIALIZE instance Real Rational #-}
349     toRational (x:%y)   =  toInteger x :% toInteger y
350
351 instance  (Integral a)  => RealFrac (Ratio a)  where
352     {-# SPECIALIZE instance RealFrac Rational #-}
353     properFraction (x:%y) = (fromInteger (toInteger q), r:%y)
354                           where (q,r) = quotRem x y
355
356 instance  (Integral a)  => Show (Ratio a)  where
357     {-# SPECIALIZE instance Show Rational #-}
358     showsPrec p (x:%y)  =  showParen (p > ratioPrec) $
359                            showsPrec ratioPrec1 x .
360                            showString " % " .
361                            -- H98 report has spaces round the %
362                            -- but we removed them [May 04]
363                            -- and added them again for consistency with
364                            -- Haskell 98 [Sep 08, #1920]
365                            showsPrec ratioPrec1 y
366
367 instance  (Integral a)  => Enum (Ratio a)  where
368     {-# SPECIALIZE instance Enum Rational #-}
369     succ x              =  x + 1
370     pred x              =  x - 1
371
372     toEnum n            =  fromIntegral n :% 1
373     fromEnum            =  fromInteger . truncate
374
375     enumFrom            =  numericEnumFrom
376     enumFromThen        =  numericEnumFromThen
377     enumFromTo          =  numericEnumFromTo
378     enumFromThenTo      =  numericEnumFromThenTo
379 \end{code}
380
381
382 %*********************************************************
383 %*                                                      *
384 \subsection{Coercions}
385 %*                                                      *
386 %*********************************************************
387
388 \begin{code}
389 -- | general coercion from integral types
390 fromIntegral :: (Integral a, Num b) => a -> b
391 fromIntegral = fromInteger . toInteger
392
393 {-# RULES
394 "fromIntegral/Int->Int" fromIntegral = id :: Int -> Int
395     #-}
396
397 -- | general coercion to fractional types
398 realToFrac :: (Real a, Fractional b) => a -> b
399 realToFrac = fromRational . toRational
400
401 {-# RULES
402 "realToFrac/Int->Int" realToFrac = id :: Int -> Int
403     #-}
404 \end{code}
405
406 %*********************************************************
407 %*                                                      *
408 \subsection{Overloaded numeric functions}
409 %*                                                      *
410 %*********************************************************
411
412 \begin{code}
413 -- | Converts a possibly-negative 'Real' value to a string.
414 showSigned :: (Real a)
415   => (a -> ShowS)       -- ^ a function that can show unsigned values
416   -> Int                -- ^ the precedence of the enclosing context
417   -> a                  -- ^ the value to show
418   -> ShowS
419 showSigned showPos p x
420    | x < 0     = showParen (p > 6) (showChar '-' . showPos (-x))
421    | otherwise = showPos x
422
423 even, odd       :: (Integral a) => a -> Bool
424 even n          =  n `rem` 2 == 0
425 odd             =  not . even
426
427 -------------------------------------------------------
428 -- | raise a number to a non-negative integral power
429 {-# SPECIALISE (^) ::
430         Integer -> Integer -> Integer,
431         Integer -> Int -> Integer,
432         Int -> Int -> Int #-}
433 {-# INLINABLE (^) #-}    -- See Note [Inlining (^)]
434 (^) :: (Num a, Integral b) => a -> b -> a
435 x0 ^ y0 | y0 < 0    = error "Negative exponent"
436         | y0 == 0   = 1
437         | otherwise = f x0 y0
438     where -- f : x0 ^ y0 = x ^ y
439           f x y | even y    = f (x * x) (y `quot` 2)
440                 | y == 1    = x
441                 | otherwise = g (x * x) ((y - 1) `quot` 2) x
442           -- g : x0 ^ y0 = (x ^ y) * z
443           g x y z | even y = g (x * x) (y `quot` 2) z
444                   | y == 1 = x * z
445                   | otherwise = g (x * x) ((y - 1) `quot` 2) (x * z)
446
447 -- | raise a number to an integral power
448 (^^)            :: (Fractional a, Integral b) => a -> b -> a
449 {-# INLINABLE (^^) #-}         -- See Note [Inlining (^)
450 x ^^ n          =  if n >= 0 then x^n else recip (x^(negate n))
451
452 {- Note [Inlining (^)
453    ~~~~~~~~~~~~~~~~~~~~~
454    The INLINABLE pragma allows (^) to be specialised at its call sites.
455    If it is called repeatedly at the same type, that can make a huge
456    difference, because of those constants which can be repeatedly
457    calculated.
458
459    Currently the fromInteger calls are not floated because we get
460              \d1 d2 x y -> blah
461    after the gentle round of simplification. -}
462
463 -------------------------------------------------------
464 -- Special power functions for Rational
465 --
466 -- see #4337
467 --
468 -- Rationale:
469 -- For a legitimate Rational (n :% d), the numerator and denominator are
470 -- coprime, i.e. they have no common prime factor.
471 -- Therefore all powers (n ^ a) and (d ^ b) are also coprime, so it is
472 -- not necessary to compute the greatest common divisor, which would be
473 -- done in the default implementation at each multiplication step.
474 -- Since exponentiation quickly leads to very large numbers and
475 -- calculation of gcds is generally very slow for large numbers,
476 -- avoiding the gcd leads to an order of magnitude speedup relatively
477 -- soon (and an asymptotic improvement overall).
478 --
479 -- Note:
480 -- We cannot use these functions for general Ratio a because that would
481 -- change results in a multitude of cases.
482 -- The cause is that if a and b are coprime, their remainders by any
483 -- positive modulus generally aren't, so in the default implementation
484 -- reduction occurs.
485 --
486 -- Example:
487 -- (17 % 3) ^ 3 :: Ratio Word8
488 -- Default:
489 -- (17 % 3) ^ 3 = ((17 % 3) ^ 2) * (17 % 3)
490 --              = ((289 `mod` 256) % 9) * (17 % 3)
491 --              = (33 % 9) * (17 % 3)
492 --              = (11 % 3) * (17 % 3)
493 --              = (187 % 9)
494 -- But:
495 -- ((17^3) `mod` 256) % (3^3)   = (4913 `mod` 256) % 27
496 --                              = 49 % 27
497 --
498 -- TODO:
499 -- Find out whether special-casing for numerator, denominator or
500 -- exponent = 1 (or -1, where that may apply) gains something.
501
502 -- Special version of (^) for Rational base
503 {-# RULES "(^)/Rational"    (^) = (^%^) #-}
504 (^%^)           :: Integral a => Rational -> a -> Rational
505 (n :% d) ^%^ e
506     | e < 0     = error "Negative exponent"
507     | e == 0    = 1 :% 1
508     | otherwise = (n ^ e) :% (d ^ e)
509
510 -- Special version of (^^) for Rational base
511 {-# RULES "(^^)/Rational"   (^^) = (^^%^^) #-}
512 (^^%^^)         :: Integral a => Rational -> a -> Rational
513 (n :% d) ^^%^^ e
514     | e > 0     = (n ^ e) :% (d ^ e)
515     | e == 0    = 1 :% 1
516     | n > 0     = (d ^ (negate e)) :% (n ^ (negate e))
517     | n == 0    = error "Ratio.%: zero denominator"
518     | otherwise = let nn = d ^ (negate e)
519                       dd = (negate n) ^ (negate e)
520                   in if even e then (nn :% dd) else (negate nn :% dd)
521
522 -------------------------------------------------------
523 -- | @'gcd' x y@ is the greatest (positive) integer that divides both @x@
524 -- and @y@; for example @'gcd' (-3) 6@ = @3@, @'gcd' (-3) (-6)@ = @3@,
525 -- @'gcd' 0 4@ = @4@.  @'gcd' 0 0@ raises a runtime error.
526 gcd             :: (Integral a) => a -> a -> a
527 gcd 0 0         =  error "Prelude.gcd: gcd 0 0 is undefined"
528 gcd x y         =  gcd' (abs x) (abs y)
529                    where gcd' a 0  =  a
530                          gcd' a b  =  gcd' b (a `rem` b)
531
532 -- | @'lcm' x y@ is the smallest positive integer that both @x@ and @y@ divide.
533 lcm             :: (Integral a) => a -> a -> a
534 {-# SPECIALISE lcm :: Int -> Int -> Int #-}
535 lcm _ 0         =  0
536 lcm 0 _         =  0
537 lcm x y         =  abs ((x `quot` (gcd x y)) * y)
538
539 #ifdef OPTIMISE_INTEGER_GCD_LCM
540 {-# RULES
541 "gcd/Int->Int->Int"             gcd = gcdInt
542 "gcd/Integer->Integer->Integer" gcd = gcdInteger'
543 "lcm/Integer->Integer->Integer" lcm = lcmInteger
544  #-}
545
546 gcdInteger' :: Integer -> Integer -> Integer
547 gcdInteger' 0 0 = error "GHC.Real.gcdInteger': gcd 0 0 is undefined"
548 gcdInteger' a b = gcdInteger a b
549
550 gcdInt :: Int -> Int -> Int
551 gcdInt 0 0 = error "GHC.Real.gcdInt: gcd 0 0 is undefined"
552 gcdInt a b = fromIntegral (gcdInteger (fromIntegral a) (fromIntegral b))
553 #endif
554
555 integralEnumFrom :: (Integral a, Bounded a) => a -> [a]
556 integralEnumFrom n = map fromInteger [toInteger n .. toInteger (maxBound `asTypeOf` n)]
557
558 integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a]
559 integralEnumFromThen n1 n2
560   | i_n2 >= i_n1  = map fromInteger [i_n1, i_n2 .. toInteger (maxBound `asTypeOf` n1)]
561   | otherwise     = map fromInteger [i_n1, i_n2 .. toInteger (minBound `asTypeOf` n1)]
562   where
563     i_n1 = toInteger n1
564     i_n2 = toInteger n2
565
566 integralEnumFromTo :: Integral a => a -> a -> [a]
567 integralEnumFromTo n m = map fromInteger [toInteger n .. toInteger m]
568
569 integralEnumFromThenTo :: Integral a => a -> a -> a -> [a]
570 integralEnumFromThenTo n1 n2 m
571   = map fromInteger [toInteger n1, toInteger n2 .. toInteger m]
572 \end{code}