10feee92c829b7da283eb0b3194e92a65698e571
[ghc-base.git] / GHC / Real.lhs
1 \begin{code}
2 {-# OPTIONS -fno-implicit-prelude #-}
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module      :  GHC.Real
6 -- Copyright   :  (c) The FFI Task Force, 1994-2002
7 -- License     :  see libraries/base/LICENSE
8 -- 
9 -- Maintainer  :  cvs-ghc@haskell.org
10 -- Stability   :  internal
11 -- Portability :  non-portable (GHC Extensions)
12 --
13 -- The types 'Ratio' and 'Rational', and the classes 'Real', 'Fractional',
14 -- 'Integral', and 'RealFrac'.
15 --
16 -----------------------------------------------------------------------------
17
18 module GHC.Real where
19
20 import {-# SOURCE #-} GHC.Err
21 import GHC.Base
22 import GHC.Num
23 import GHC.List
24 import GHC.Enum
25 import GHC.Show
26
27 infixr 8  ^, ^^
28 infixl 7  /, `quot`, `rem`, `div`, `mod`
29 infixl 7  %
30
31 default ()              -- Double isn't available yet, 
32                         -- and we shouldn't be using defaults anyway
33 \end{code}
34
35
36 %*********************************************************
37 %*                                                      *
38 \subsection{The @Ratio@ and @Rational@ types}
39 %*                                                      *
40 %*********************************************************
41
42 \begin{code}
43 -- | Rational numbers, with numerator and denominator of some 'Integral' type.
44 data  (Integral a)      => Ratio a = !a :% !a  deriving (Eq)
45
46 -- | Arbitrary-precision rational numbers, represented as a ratio of
47 -- two 'Integer' values.  A rational number may be constructed using
48 -- the '%' operator.
49 type  Rational          =  Ratio Integer
50
51 ratioPrec, ratioPrec1 :: Int
52 ratioPrec  = 7  -- Precedence of ':%' constructor
53 ratioPrec1 = ratioPrec + 1
54
55 infinity, notANumber :: Rational
56 infinity   = 1 :% 0
57 notANumber = 0 :% 0
58
59 -- Use :%, not % for Inf/NaN; the latter would 
60 -- immediately lead to a runtime error, because it normalises. 
61 \end{code}
62
63
64 \begin{code}
65 -- | Forms the ratio of two integral numbers.
66 {-# SPECIALISE (%) :: Integer -> Integer -> Rational #-}
67 (%)                     :: (Integral a) => a -> a -> Ratio a
68
69 -- | Extract the numerator of the ratio in reduced form:
70 -- the numerator and denominator have no common factor and the denominator
71 -- is positive.
72 numerator       :: (Integral a) => Ratio a -> a
73
74 -- | Extract the denominator of the ratio in reduced form:
75 -- the numerator and denominator have no common factor and the denominator
76 -- is positive.
77 denominator     :: (Integral a) => Ratio a -> a
78 \end{code}
79
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.
83
84 \begin{code}
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)
89                            where d = gcd x y
90 \end{code}
91
92 \begin{code}
93 x % y                   =  reduce (x * signum y) (abs y)
94
95 numerator   (x :% _)    =  x
96 denominator (_ :% y)    =  y
97 \end{code}
98
99
100 %*********************************************************
101 %*                                                      *
102 \subsection{Standard numeric classes}
103 %*                                                      *
104 %*********************************************************
105
106 \begin{code}
107 class  (Num a, Ord a) => Real a  where
108     -- | the rational equivalent of its real argument with full precision
109     toRational          ::  a -> Rational
110
111 -- | Integral numbers, supporting integer division.
112 --
113 -- Minimal complete definition: 'quotRem' and 'toInteger'
114 class  (Real a, Enum a) => Integral a  where
115     -- | integer division truncated toward zero
116     quot                :: a -> a -> a
117     -- | integer remainder, satisfying
118     --
119     -- > (x `quot` y)*y + (x `rem` y) == x
120     rem                 :: a -> a -> a
121     -- | integer division truncated toward negative infinity
122     div                 :: a -> a -> a
123     -- | integer modulus, satisfying
124     --
125     -- > (x `div` y)*y + (x `mod` y) == x
126     mod                 :: a -> a -> a
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
133
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
140
141 -- | Fractional numbers, supporting real division.
142 --
143 -- Minimal complete definition: 'fromRational' and ('recip' or @('/')@)
144 class  (Num a) => Fractional a  where
145     -- | fractional division
146     (/)                 :: a -> a -> a
147     -- | reciprocal fraction
148     recip               :: a -> a
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
154
155     recip x             =  1 / x
156     x / y               = x * recip y
157
158 -- | Extracting components of fractions.
159 --
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:
164     --
165     -- * @n@ is an integral number with the same sign as @x@; and
166     --
167     -- * @f@ is a fraction with the same type and sign as @x@,
168     --   and with absolute value less than @1@.
169     --
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
181
182     truncate x          =  m  where (m,_) = properFraction x
183     
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
187                                 -1 -> n
188                                 0  -> if even n then n else m
189                                 1  -> m
190     
191     ceiling x           =  if r > 0 then n + 1 else n
192                            where (n,r) = properFraction x
193     
194     floor x             =  if r < 0 then n - 1 else n
195                            where (n,r) = properFraction x
196 \end{code}
197
198
199 These 'numeric' enumerations come straight from the Report
200
201 \begin{code}
202 numericEnumFrom         :: (Fractional a) => a -> [a]
203 numericEnumFrom         =  iterate (+1)
204
205 numericEnumFromThen     :: (Fractional a) => a -> a -> [a]
206 numericEnumFromThen n m =  iterate (+(m-n)) n
207
208 numericEnumFromTo       :: (Ord a, Fractional a) => a -> a -> [a]
209 numericEnumFromTo n m   = takeWhile (<= m + 1/2) (numericEnumFrom n)
210
211 numericEnumFromThenTo   :: (Ord a, Fractional a) => a -> a -> a -> [a]
212 numericEnumFromThenTo e1 e2 e3 = takeWhile pred (numericEnumFromThen e1 e2)
213                                 where
214                                  mid = (e2 - e1) / 2
215                                  pred | e2 >= e1  = (<= e3 + mid)
216                                       | otherwise = (>= e3 + mid)
217 \end{code}
218
219
220 %*********************************************************
221 %*                                                      *
222 \subsection{Instances for @Int@}
223 %*                                                      *
224 %*********************************************************
225
226 \begin{code}
227 instance  Real Int  where
228     toRational x        =  toInteger x % 1
229
230 instance  Integral Int  where
231     toInteger i = int2Integer i  -- give back a full-blown Integer
232
233     a `quot` 0   = divZeroError
234     a `quot` b  =  a `quotInt` b
235
236     a `rem` 0   = divZeroError
237     a `rem` b   = a `remInt` b
238
239     a `div` 0   = divZeroError
240     a `div` b   = a `divInt` b
241
242     a `mod` 0   = divZeroError
243     a `mod` b   = a `modInt` b
244
245     a `quotRem` 0 = divZeroError
246     a `quotRem` b = a `quotRemInt` b
247
248     a `divMod`  0 = divZeroError
249     a `divMod`  b = a `divModInt`  b
250 \end{code}
251
252
253 %*********************************************************
254 %*                                                      *
255 \subsection{Instances for @Integer@}
256 %*                                                      *
257 %*********************************************************
258
259 \begin{code}
260 instance  Real Integer  where
261     toRational x        =  x % 1
262
263 instance  Integral Integer where
264     toInteger n      = n
265
266     a `quot` 0 = divZeroError
267     n `quot` d = n `quotInteger` d
268
269     a `rem` 0 = divZeroError
270     n `rem`  d = n `remInteger`  d
271
272     a `divMod` 0 = divZeroError
273     a `divMod` b = a `divModInteger` b
274
275     a `quotRem` 0 = divZeroError
276     a `quotRem` b = a `quotRemInteger` b
277
278     -- use the defaults for div & mod
279 \end{code}
280
281
282 %*********************************************************
283 %*                                                      *
284 \subsection{Instances for @Ratio@}
285 %*                                                      *
286 %*********************************************************
287
288 \begin{code}
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
293
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
303
304 instance  (Integral a)  => Fractional (Ratio a)  where
305     {-# SPECIALIZE instance Fractional Rational #-}
306     (x:%y) / (x':%y')   =  (x*y') % (y*x')
307     recip (x:%y)        =  y % x
308     fromRational (x:%y) =  fromInteger x :% fromInteger y
309
310 instance  (Integral a)  => Real (Ratio a)  where
311     {-# SPECIALIZE instance Real Rational #-}
312     toRational (x:%y)   =  toInteger x :% toInteger y
313
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
318
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
326
327 instance  (Integral a)  => Enum (Ratio a)  where
328     {-# SPECIALIZE instance Enum Rational #-}
329     succ x              =  x + 1
330     pred x              =  x - 1
331
332     toEnum n            =  fromInteger (int2Integer n) :% 1
333     fromEnum            =  fromInteger . truncate
334
335     enumFrom            =  numericEnumFrom
336     enumFromThen        =  numericEnumFromThen
337     enumFromTo          =  numericEnumFromTo
338     enumFromThenTo      =  numericEnumFromThenTo
339 \end{code}
340
341
342 %*********************************************************
343 %*                                                      *
344 \subsection{Coercions}
345 %*                                                      *
346 %*********************************************************
347
348 \begin{code}
349 -- | general coercion from integral types
350 fromIntegral :: (Integral a, Num b) => a -> b
351 fromIntegral = fromInteger . toInteger
352
353 {-# RULES
354 "fromIntegral/Int->Int" fromIntegral = id :: Int -> Int
355     #-}
356
357 -- | general coercion to fractional types
358 realToFrac :: (Real a, Fractional b) => a -> b
359 realToFrac = fromRational . toRational
360
361 {-# RULES
362 "realToFrac/Int->Int" realToFrac = id :: Int -> Int
363     #-}
364 \end{code}
365
366 %*********************************************************
367 %*                                                      *
368 \subsection{Overloaded numeric functions}
369 %*                                                      *
370 %*********************************************************
371
372 \begin{code}
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
378   -> ShowS
379 showSigned showPos p x 
380    | x < 0     = showParen (p > 6) (showChar '-' . showPos (-x))
381    | otherwise = showPos x
382
383 even, odd       :: (Integral a) => a -> Bool
384 even n          =  n `rem` 2 == 0
385 odd             =  not . even
386
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
394 _ ^ 0           =  1
395 x ^ n | n > 0   =  f x (n-1) x
396                    where f _ 0 y = y
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"
401
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))
407
408
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)
416                    where gcd' a 0  =  a
417                          gcd' a b  =  gcd' b (a `rem` b)
418
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 #-}
422 lcm _ 0         =  0
423 lcm 0 _         =  0
424 lcm x y         =  abs ((x `quot` (gcd x y)) * y)
425
426
427 {-# RULES
428 "gcd/Int->Int->Int"             gcd = gcdInt
429 "gcd/Integer->Integer->Integer" gcd = gcdInteger
430 "lcm/Integer->Integer->Integer" lcm = lcmInteger
431  #-}
432
433 integralEnumFrom :: (Integral a, Bounded a) => a -> [a]
434 integralEnumFrom n = map fromInteger [toInteger n .. toInteger (maxBound `asTypeOf` n)]
435
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)]
440   where
441     i_n1 = toInteger n1
442     i_n2 = toInteger n2
443
444 integralEnumFromTo :: Integral a => a -> a -> [a]
445 integralEnumFromTo n m = map fromInteger [toInteger n .. toInteger m]
446
447 integralEnumFromThenTo :: Integral a => a -> a -> a -> [a]
448 integralEnumFromThenTo n1 n2 m
449   = map fromInteger [toInteger n1, toInteger n2 .. toInteger m]
450 \end{code}