Turn off the gcd/lcm optimisations for Integer for now
[ghc-base.git] / GHC / Real.lhs
1 \begin{code}
2 {-# OPTIONS_GHC -fno-implicit-prelude #-}
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     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
182
183     truncate x          =  m  where (m,_) = properFraction x
184     
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
188                                 -1 -> n
189                                 0  -> if even n then n else m
190                                 1  -> m
191     
192     ceiling x           =  if r > 0 then n + 1 else n
193                            where (n,r) = properFraction x
194     
195     floor x             =  if r < 0 then n - 1 else n
196                            where (n,r) = properFraction x
197 \end{code}
198
199
200 These 'numeric' enumerations come straight from the Report
201
202 \begin{code}
203 numericEnumFrom         :: (Fractional a) => a -> [a]
204 numericEnumFrom         =  iterate (+1)
205
206 numericEnumFromThen     :: (Fractional a) => a -> a -> [a]
207 numericEnumFromThen n m =  iterate (+(m-n)) n
208
209 numericEnumFromTo       :: (Ord a, Fractional a) => a -> a -> [a]
210 numericEnumFromTo n m   = takeWhile (<= m + 1/2) (numericEnumFrom n)
211
212 numericEnumFromThenTo   :: (Ord a, Fractional a) => a -> a -> a -> [a]
213 numericEnumFromThenTo e1 e2 e3 = takeWhile pred (numericEnumFromThen e1 e2)
214                                 where
215                                  mid = (e2 - e1) / 2
216                                  pred | e2 >= e1  = (<= e3 + mid)
217                                       | otherwise = (>= e3 + mid)
218 \end{code}
219
220
221 %*********************************************************
222 %*                                                      *
223 \subsection{Instances for @Int@}
224 %*                                                      *
225 %*********************************************************
226
227 \begin{code}
228 instance  Real Int  where
229     toRational x        =  toInteger x % 1
230
231 instance  Integral Int  where
232     toInteger (I# i) = smallInteger i
233
234     a `quot` b
235      | b == 0                     = divZeroError
236      | a == minBound && b == (-1) = overflowError
237      | otherwise                  =  a `quotInt` b
238
239     a `rem` b
240      | b == 0                     = divZeroError
241      | a == minBound && b == (-1) = overflowError
242      | otherwise                  =  a `remInt` b
243
244     a `div` b
245      | b == 0                     = divZeroError
246      | a == minBound && b == (-1) = overflowError
247      | otherwise                  =  a `divInt` b
248
249     a `mod` b
250      | b == 0                     = divZeroError
251      | a == minBound && b == (-1) = overflowError
252      | otherwise                  =  a `modInt` b
253
254     a `quotRem` b
255      | b == 0                     = divZeroError
256      | a == minBound && b == (-1) = overflowError
257      | otherwise                  =  a `quotRemInt` b
258
259     a `divMod` b
260      | b == 0                     = divZeroError
261      | a == minBound && b == (-1) = overflowError
262      | otherwise                  =  a `divModInt` b
263 \end{code}
264
265
266 %*********************************************************
267 %*                                                      *
268 \subsection{Instances for @Integer@}
269 %*                                                      *
270 %*********************************************************
271
272 \begin{code}
273 instance  Real Integer  where
274     toRational x        =  x % 1
275
276 instance  Integral Integer where
277     toInteger n      = n
278
279     a `quot` 0 = divZeroError
280     n `quot` d = n `quotInteger` d
281
282     a `rem` 0 = divZeroError
283     n `rem`  d = n `remInteger`  d
284
285     a `divMod` 0 = divZeroError
286     a `divMod` b = case a `divModInteger` b of
287                    (# x, y #) -> (x, y)
288
289     a `quotRem` 0 = divZeroError
290     a `quotRem` b = case a `quotRemInteger` b of
291                     (# q, r #) -> (q, r)
292
293     -- use the defaults for div & mod
294 \end{code}
295
296
297 %*********************************************************
298 %*                                                      *
299 \subsection{Instances for @Ratio@}
300 %*                                                      *
301 %*********************************************************
302
303 \begin{code}
304 instance  (Integral a)  => Ord (Ratio a)  where
305     {-# SPECIALIZE instance Ord Rational #-}
306     (x:%y) <= (x':%y')  =  x * y' <= x' * y
307     (x:%y) <  (x':%y')  =  x * y' <  x' * y
308
309 instance  (Integral a)  => Num (Ratio a)  where
310     {-# SPECIALIZE instance Num Rational #-}
311     (x:%y) + (x':%y')   =  reduce (x*y' + x'*y) (y*y')
312     (x:%y) - (x':%y')   =  reduce (x*y' - x'*y) (y*y')
313     (x:%y) * (x':%y')   =  reduce (x * x') (y * y')
314     negate (x:%y)       =  (-x) :% y
315     abs (x:%y)          =  abs x :% y
316     signum (x:%_)       =  signum x :% 1
317     fromInteger x       =  fromInteger x :% 1
318
319 instance  (Integral a)  => Fractional (Ratio a)  where
320     {-# SPECIALIZE instance Fractional Rational #-}
321     (x:%y) / (x':%y')   =  (x*y') % (y*x')
322     recip (x:%y)        =  y % x
323     fromRational (x:%y) =  fromInteger x :% fromInteger y
324
325 instance  (Integral a)  => Real (Ratio a)  where
326     {-# SPECIALIZE instance Real Rational #-}
327     toRational (x:%y)   =  toInteger x :% toInteger y
328
329 instance  (Integral a)  => RealFrac (Ratio a)  where
330     {-# SPECIALIZE instance RealFrac Rational #-}
331     properFraction (x:%y) = (fromInteger (toInteger q), r:%y)
332                           where (q,r) = quotRem x y
333
334 instance  (Integral a)  => Show (Ratio a)  where
335     {-# SPECIALIZE instance Show Rational #-}
336     showsPrec p (x:%y)  =  showParen (p > ratioPrec) $
337                            showsPrec ratioPrec1 x . 
338                            showString "%" .     -- H98 report has spaces round the %
339                                                 -- but we removed them [May 04]
340                            showsPrec ratioPrec1 y
341
342 instance  (Integral a)  => Enum (Ratio a)  where
343     {-# SPECIALIZE instance Enum Rational #-}
344     succ x              =  x + 1
345     pred x              =  x - 1
346
347     toEnum n            =  fromIntegral n :% 1
348     fromEnum            =  fromInteger . truncate
349
350     enumFrom            =  numericEnumFrom
351     enumFromThen        =  numericEnumFromThen
352     enumFromTo          =  numericEnumFromTo
353     enumFromThenTo      =  numericEnumFromThenTo
354 \end{code}
355
356
357 %*********************************************************
358 %*                                                      *
359 \subsection{Coercions}
360 %*                                                      *
361 %*********************************************************
362
363 \begin{code}
364 -- | general coercion from integral types
365 fromIntegral :: (Integral a, Num b) => a -> b
366 fromIntegral = fromInteger . toInteger
367
368 {-# RULES
369 "fromIntegral/Int->Int" fromIntegral = id :: Int -> Int
370     #-}
371
372 -- | general coercion to fractional types
373 realToFrac :: (Real a, Fractional b) => a -> b
374 realToFrac = fromRational . toRational
375
376 {-# RULES
377 "realToFrac/Int->Int" realToFrac = id :: Int -> Int
378     #-}
379 \end{code}
380
381 %*********************************************************
382 %*                                                      *
383 \subsection{Overloaded numeric functions}
384 %*                                                      *
385 %*********************************************************
386
387 \begin{code}
388 -- | Converts a possibly-negative 'Real' value to a string.
389 showSigned :: (Real a)
390   => (a -> ShowS)       -- ^ a function that can show unsigned values
391   -> Int                -- ^ the precedence of the enclosing context
392   -> a                  -- ^ the value to show
393   -> ShowS
394 showSigned showPos p x 
395    | x < 0     = showParen (p > 6) (showChar '-' . showPos (-x))
396    | otherwise = showPos x
397
398 even, odd       :: (Integral a) => a -> Bool
399 even n          =  n `rem` 2 == 0
400 odd             =  not . even
401
402 -------------------------------------------------------
403 -- | raise a number to a non-negative integral power
404 {-# SPECIALISE (^) ::
405         Integer -> Integer -> Integer,
406         Integer -> Int -> Integer,
407         Int -> Int -> Int #-}
408 (^) :: (Num a, Integral b) => a -> b -> a
409 x0 ^ y0 | y0 < 0    = error "Negative exponent"
410         | y0 == 0   = 1
411         | otherwise = f x0 y0 1
412     where -- x0 ^ y0 = (x ^ y) * z
413           f x y z | even y = f (x * x) (y `quot` 2) z
414                   | y == 1 = x * z
415                   | otherwise = f (x * x) ((y - 1) `quot` 2) (x * z)
416
417 -- | raise a number to an integral power
418 {-# SPECIALISE (^^) ::
419         Rational -> Int -> Rational #-}
420 (^^)            :: (Fractional a, Integral b) => a -> b -> a
421 x ^^ n          =  if n >= 0 then x^n else recip (x^(negate n))
422
423
424 -------------------------------------------------------
425 -- | @'gcd' x y@ is the greatest (positive) integer that divides both @x@
426 -- and @y@; for example @'gcd' (-3) 6@ = @3@, @'gcd' (-3) (-6)@ = @3@,
427 -- @'gcd' 0 4@ = @4@.  @'gcd' 0 0@ raises a runtime error.
428 gcd             :: (Integral a) => a -> a -> a
429 gcd 0 0         =  error "Prelude.gcd: gcd 0 0 is undefined"
430 gcd x y         =  gcd' (abs x) (abs y)
431                    where gcd' a 0  =  a
432                          gcd' a b  =  gcd' b (a `rem` b)
433
434 -- | @'lcm' x y@ is the smallest positive integer that both @x@ and @y@ divide.
435 lcm             :: (Integral a) => a -> a -> a
436 {-# SPECIALISE lcm :: Int -> Int -> Int #-}
437 lcm _ 0         =  0
438 lcm 0 _         =  0
439 lcm x y         =  abs ((x `quot` (gcd x y)) * y)
440
441 {-# RULES
442 "gcd/Int->Int->Int"             gcd = gcdInt
443  #-}
444
445 -- XXX these optimisation rules are disabled for now to make it easier
446 --     to experiment with other Integer implementations
447 -- "gcd/Integer->Integer->Integer" gcd = gcdInteger'
448 -- "lcm/Integer->Integer->Integer" lcm = lcmInteger
449 --
450 -- gcdInteger' :: Integer -> Integer -> Integer
451 -- gcdInteger' 0 0 = error "GHC.Real.gcdInteger': gcd 0 0 is undefined"
452 -- gcdInteger' a b = gcdInteger a b
453
454 integralEnumFrom :: (Integral a, Bounded a) => a -> [a]
455 integralEnumFrom n = map fromInteger [toInteger n .. toInteger (maxBound `asTypeOf` n)]
456
457 integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a]
458 integralEnumFromThen n1 n2
459   | i_n2 >= i_n1  = map fromInteger [i_n1, i_n2 .. toInteger (maxBound `asTypeOf` n1)]
460   | otherwise     = map fromInteger [i_n1, i_n2 .. toInteger (minBound `asTypeOf` n1)]
461   where
462     i_n1 = toInteger n1
463     i_n2 = toInteger n2
464
465 integralEnumFromTo :: Integral a => a -> a -> [a]
466 integralEnumFromTo n m = map fromInteger [toInteger n .. toInteger m]
467
468 integralEnumFromThenTo :: Integral a => a -> a -> a -> [a]
469 integralEnumFromThenTo n1 n2 m
470   = map fromInteger [toInteger n1, toInteger n2 .. toInteger m]
471 \end{code}