add Data.Sequence to nhc98 build
[haskell-directory.git] / GHC / Real.lhs
1 \begin{code}
2 {-# OPTIONS_GHC -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 -- #hide
19 module GHC.Real where
20
21 import {-# SOURCE #-} GHC.Err
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 = int2Integer i  -- give back a full-blown Integer
233
234     a `quot` 0   = divZeroError
235     a `quot` b  =  a `quotInt` b
236
237     a `rem` 0   = divZeroError
238     a `rem` b   = a `remInt` b
239
240     a `div` 0   = divZeroError
241     a `div` b   = a `divInt` b
242
243     a `mod` 0   = divZeroError
244     a `mod` b   = a `modInt` b
245
246     a `quotRem` 0 = divZeroError
247     a `quotRem` b = a `quotRemInt` b
248
249     a `divMod`  0 = divZeroError
250     a `divMod`  b = a `divModInt`  b
251 \end{code}
252
253
254 %*********************************************************
255 %*                                                      *
256 \subsection{Instances for @Integer@}
257 %*                                                      *
258 %*********************************************************
259
260 \begin{code}
261 instance  Real Integer  where
262     toRational x        =  x % 1
263
264 instance  Integral Integer where
265     toInteger n      = n
266
267     a `quot` 0 = divZeroError
268     n `quot` d = n `quotInteger` d
269
270     a `rem` 0 = divZeroError
271     n `rem`  d = n `remInteger`  d
272
273     a `divMod` 0 = divZeroError
274     a `divMod` b = a `divModInteger` b
275
276     a `quotRem` 0 = divZeroError
277     a `quotRem` b = a `quotRemInteger` b
278
279     -- use the defaults for div & mod
280 \end{code}
281
282
283 %*********************************************************
284 %*                                                      *
285 \subsection{Instances for @Ratio@}
286 %*                                                      *
287 %*********************************************************
288
289 \begin{code}
290 instance  (Integral a)  => Ord (Ratio a)  where
291     {-# SPECIALIZE instance Ord Rational #-}
292     (x:%y) <= (x':%y')  =  x * y' <= x' * y
293     (x:%y) <  (x':%y')  =  x * y' <  x' * y
294
295 instance  (Integral a)  => Num (Ratio a)  where
296     {-# SPECIALIZE instance Num Rational #-}
297     (x:%y) + (x':%y')   =  reduce (x*y' + x'*y) (y*y')
298     (x:%y) - (x':%y')   =  reduce (x*y' - x'*y) (y*y')
299     (x:%y) * (x':%y')   =  reduce (x * x') (y * y')
300     negate (x:%y)       =  (-x) :% y
301     abs (x:%y)          =  abs x :% y
302     signum (x:%_)       =  signum x :% 1
303     fromInteger x       =  fromInteger x :% 1
304
305 instance  (Integral a)  => Fractional (Ratio a)  where
306     {-# SPECIALIZE instance Fractional Rational #-}
307     (x:%y) / (x':%y')   =  (x*y') % (y*x')
308     recip (x:%y)        =  y % x
309     fromRational (x:%y) =  fromInteger x :% fromInteger y
310
311 instance  (Integral a)  => Real (Ratio a)  where
312     {-# SPECIALIZE instance Real Rational #-}
313     toRational (x:%y)   =  toInteger x :% toInteger y
314
315 instance  (Integral a)  => RealFrac (Ratio a)  where
316     {-# SPECIALIZE instance RealFrac Rational #-}
317     properFraction (x:%y) = (fromInteger (toInteger q), r:%y)
318                           where (q,r) = quotRem x y
319
320 instance  (Integral a)  => Show (Ratio a)  where
321     {-# SPECIALIZE instance Show Rational #-}
322     showsPrec p (x:%y)  =  showParen (p > ratioPrec) $
323                            showsPrec ratioPrec1 x . 
324                            showString "%" .     -- H98 report has spaces round the %
325                                                 -- but we removed them [May 04]
326                            showsPrec ratioPrec1 y
327
328 instance  (Integral a)  => Enum (Ratio a)  where
329     {-# SPECIALIZE instance Enum Rational #-}
330     succ x              =  x + 1
331     pred x              =  x - 1
332
333     toEnum n            =  fromInteger (int2Integer n) :% 1
334     fromEnum            =  fromInteger . truncate
335
336     enumFrom            =  numericEnumFrom
337     enumFromThen        =  numericEnumFromThen
338     enumFromTo          =  numericEnumFromTo
339     enumFromThenTo      =  numericEnumFromThenTo
340 \end{code}
341
342
343 %*********************************************************
344 %*                                                      *
345 \subsection{Coercions}
346 %*                                                      *
347 %*********************************************************
348
349 \begin{code}
350 -- | general coercion from integral types
351 fromIntegral :: (Integral a, Num b) => a -> b
352 fromIntegral = fromInteger . toInteger
353
354 {-# RULES
355 "fromIntegral/Int->Int" fromIntegral = id :: Int -> Int
356     #-}
357
358 -- | general coercion to fractional types
359 realToFrac :: (Real a, Fractional b) => a -> b
360 realToFrac = fromRational . toRational
361
362 {-# RULES
363 "realToFrac/Int->Int" realToFrac = id :: Int -> Int
364     #-}
365 \end{code}
366
367 %*********************************************************
368 %*                                                      *
369 \subsection{Overloaded numeric functions}
370 %*                                                      *
371 %*********************************************************
372
373 \begin{code}
374 -- | Converts a possibly-negative 'Real' value to a string.
375 showSigned :: (Real a)
376   => (a -> ShowS)       -- ^ a function that can show unsigned values
377   -> Int                -- ^ the precedence of the enclosing context
378   -> a                  -- ^ the value to show
379   -> ShowS
380 showSigned showPos p x 
381    | x < 0     = showParen (p > 6) (showChar '-' . showPos (-x))
382    | otherwise = showPos x
383
384 even, odd       :: (Integral a) => a -> Bool
385 even n          =  n `rem` 2 == 0
386 odd             =  not . even
387
388 -------------------------------------------------------
389 -- | raise a number to a non-negative integral power
390 {-# SPECIALISE (^) ::
391         Integer -> Integer -> Integer,
392         Integer -> Int -> Integer,
393         Int -> Int -> Int #-}
394 (^)             :: (Num a, Integral b) => a -> b -> a
395 _ ^ 0           =  1
396 x ^ n | n > 0   =  f x (n-1) x
397                    where f _ 0 y = y
398                          f a d y = g a d  where
399                                    g b i | even i  = g (b*b) (i `quot` 2)
400                                          | otherwise = f b (i-1) (b*y)
401 _ ^ _           = error "Prelude.^: negative exponent"
402
403 -- | raise a number to an integral power
404 {-# SPECIALISE (^^) ::
405         Rational -> Int -> Rational #-}
406 (^^)            :: (Fractional a, Integral b) => a -> b -> a
407 x ^^ n          =  if n >= 0 then x^n else recip (x^(negate n))
408
409
410 -------------------------------------------------------
411 -- | @'gcd' x y@ is the greatest (positive) integer that divides both @x@
412 -- and @y@; for example @'gcd' (-3) 6@ = @3@, @'gcd' (-3) (-6)@ = @3@,
413 -- @'gcd' 0 4@ = @4@.  @'gcd' 0 0@ raises a runtime error.
414 gcd             :: (Integral a) => a -> a -> a
415 gcd 0 0         =  error "Prelude.gcd: gcd 0 0 is undefined"
416 gcd x y         =  gcd' (abs x) (abs y)
417                    where gcd' a 0  =  a
418                          gcd' a b  =  gcd' b (a `rem` b)
419
420 -- | @'lcm' x y@ is the smallest positive integer that both @x@ and @y@ divide.
421 lcm             :: (Integral a) => a -> a -> a
422 {-# SPECIALISE lcm :: Int -> Int -> Int #-}
423 lcm _ 0         =  0
424 lcm 0 _         =  0
425 lcm x y         =  abs ((x `quot` (gcd x y)) * y)
426
427
428 {-# RULES
429 "gcd/Int->Int->Int"             gcd = gcdInt
430 "gcd/Integer->Integer->Integer" gcd = gcdInteger
431 "lcm/Integer->Integer->Integer" lcm = lcmInteger
432  #-}
433
434 integralEnumFrom :: (Integral a, Bounded a) => a -> [a]
435 integralEnumFrom n = map fromInteger [toInteger n .. toInteger (maxBound `asTypeOf` n)]
436
437 integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a]
438 integralEnumFromThen n1 n2
439   | i_n2 >= i_n1  = map fromInteger [i_n1, i_n2 .. toInteger (maxBound `asTypeOf` n1)]
440   | otherwise     = map fromInteger [i_n1, i_n2 .. toInteger (minBound `asTypeOf` n1)]
441   where
442     i_n1 = toInteger n1
443     i_n2 = toInteger n2
444
445 integralEnumFromTo :: Integral a => a -> a -> [a]
446 integralEnumFromTo n m = map fromInteger [toInteger n .. toInteger m]
447
448 integralEnumFromThenTo :: Integral a => a -> a -> a -> [a]
449 integralEnumFromThenTo n1 n2 m
450   = map fromInteger [toInteger n1, toInteger n2 .. toInteger m]
451 \end{code}