[project @ 2002-07-23 14:52:46 by simonpj]
[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
30 default ()              -- Double isn't available yet, 
31                         -- and we shouldn't be using defaults anyway
32 \end{code}
33
34
35 %*********************************************************
36 %*                                                      *
37 \subsection{The @Ratio@ and @Rational@ types}
38 %*                                                      *
39 %*********************************************************
40
41 \begin{code}
42 data  (Integral a)      => Ratio a = !a :% !a  deriving (Eq)
43
44 -- | Arbitrary-precision rational numbers, represented as a ratio of
45 -- two 'Integer' values.  A rational number may be constructed using
46 -- the '%' operator.
47 type  Rational          =  Ratio Integer
48
49 ratioPrec, ratioPrec1 :: Int
50 ratioPrec  = 7  -- Precedence of ':%' constructor
51 ratioPrec1 = ratioPrec + 1
52
53 infinity, notANumber :: Rational
54 infinity   = 1 :% 0
55 notANumber = 0 :% 0
56
57 -- Use :%, not % for Inf/NaN; the latter would 
58 -- immediately lead to a runtime error, because it normalises. 
59 \end{code}
60
61
62 \begin{code}
63 {-# SPECIALISE (%) :: Integer -> Integer -> Rational #-}
64 (%)                     :: (Integral a) => a -> a -> Ratio a
65 numerator, denominator  :: (Integral a) => Ratio a -> a
66 \end{code}
67
68 \tr{reduce} is a subsidiary function used only in this module .
69 It normalises a ratio by dividing both numerator and denominator by
70 their greatest common divisor.
71
72 \begin{code}
73 reduce ::  (Integral a) => a -> a -> Ratio a
74 {-# SPECIALISE reduce :: Integer -> Integer -> Rational #-}
75 reduce _ 0              =  error "Ratio.%: zero denominator"
76 reduce x y              =  (x `quot` d) :% (y `quot` d)
77                            where d = gcd x y
78 \end{code}
79
80 \begin{code}
81 x % y                   =  reduce (x * signum y) (abs y)
82
83 numerator   (x :% _)    =  x
84 denominator (_ :% y)    =  y
85 \end{code}
86
87
88 %*********************************************************
89 %*                                                      *
90 \subsection{Standard numeric classes}
91 %*                                                      *
92 %*********************************************************
93
94 \begin{code}
95 class  (Num a, Ord a) => Real a  where
96     toRational          ::  a -> Rational
97
98 class  (Real a, Enum a) => Integral a  where
99     quot, rem, div, mod :: a -> a -> a
100     quotRem, divMod     :: a -> a -> (a,a)
101     toInteger           :: a -> Integer
102
103     n `quot` d          =  q  where (q,_) = quotRem n d
104     n `rem` d           =  r  where (_,r) = quotRem n d
105     n `div` d           =  q  where (q,_) = divMod n d
106     n `mod` d           =  r  where (_,r) = divMod n d
107     divMod n d          =  if signum r == negate (signum d) then (q-1, r+d) else qr
108                            where qr@(q,r) = quotRem n d
109
110 class  (Num a) => Fractional a  where
111     (/)                 :: a -> a -> a
112     recip               :: a -> a
113     fromRational        :: Rational -> a
114
115     recip x             =  1 / x
116     x / y               = x * recip y
117
118 class  (Real a, Fractional a) => RealFrac a  where
119     properFraction      :: (Integral b) => a -> (b,a)
120     truncate, round     :: (Integral b) => a -> b
121     ceiling, floor      :: (Integral b) => a -> b
122
123     truncate x          =  m  where (m,_) = properFraction x
124     
125     round x             =  let (n,r) = properFraction x
126                                m     = if r < 0 then n - 1 else n + 1
127                            in case signum (abs r - 0.5) of
128                                 -1 -> n
129                                 0  -> if even n then n else m
130                                 1  -> m
131     
132     ceiling x           =  if r > 0 then n + 1 else n
133                            where (n,r) = properFraction x
134     
135     floor x             =  if r < 0 then n - 1 else n
136                            where (n,r) = properFraction x
137 \end{code}
138
139
140 These 'numeric' enumerations come straight from the Report
141
142 \begin{code}
143 numericEnumFrom         :: (Fractional a) => a -> [a]
144 numericEnumFrom         =  iterate (+1)
145
146 numericEnumFromThen     :: (Fractional a) => a -> a -> [a]
147 numericEnumFromThen n m =  iterate (+(m-n)) n
148
149 numericEnumFromTo       :: (Ord a, Fractional a) => a -> a -> [a]
150 numericEnumFromTo n m   = takeWhile (<= m + 1/2) (numericEnumFrom n)
151
152 numericEnumFromThenTo   :: (Ord a, Fractional a) => a -> a -> a -> [a]
153 numericEnumFromThenTo e1 e2 e3 = takeWhile pred (numericEnumFromThen e1 e2)
154                                 where
155                                  mid = (e2 - e1) / 2
156                                  pred | e2 > e1   = (<= e3 + mid)
157                                       | otherwise = (>= e3 + mid)
158 \end{code}
159
160
161 %*********************************************************
162 %*                                                      *
163 \subsection{Instances for @Int@}
164 %*                                                      *
165 %*********************************************************
166
167 \begin{code}
168 instance  Real Int  where
169     toRational x        =  toInteger x % 1
170
171 instance  Integral Int  where
172     toInteger i = int2Integer i  -- give back a full-blown Integer
173
174     -- Following chks for zero divisor are non-standard (WDP)
175     a `quot` b  =  if b /= 0
176                    then a `quotInt` b
177                    else error "Prelude.Integral.quot{Int}: divide by 0"
178     a `rem` b   =  if b /= 0
179                    then a `remInt` b
180                    else error "Prelude.Integral.rem{Int}: divide by 0"
181
182     x `div` y = x `divInt` y
183     x `mod` y = x `modInt` y
184
185     a `quotRem` b = a `quotRemInt` b
186     a `divMod`  b = a `divModInt`  b
187 \end{code}
188
189
190 %*********************************************************
191 %*                                                      *
192 \subsection{Instances for @Integer@}
193 %*                                                      *
194 %*********************************************************
195
196 \begin{code}
197 instance  Real Integer  where
198     toRational x        =  x % 1
199
200 instance  Integral Integer where
201     toInteger n      = n
202
203     n `quot` d = n `quotInteger` d
204     n `rem`  d = n `remInteger`  d
205
206     n `div` d   =  q  where (q,_) = divMod n d
207     n `mod` d   =  r  where (_,r) = divMod n d
208
209     a `divMod` b = a `divModInteger` b
210     a `quotRem` b = a `quotRemInteger` b
211 \end{code}
212
213
214 %*********************************************************
215 %*                                                      *
216 \subsection{Instances for @Ratio@}
217 %*                                                      *
218 %*********************************************************
219
220 \begin{code}
221 instance  (Integral a)  => Ord (Ratio a)  where
222     {-# SPECIALIZE instance Ord Rational #-}
223     (x:%y) <= (x':%y')  =  x * y' <= x' * y
224     (x:%y) <  (x':%y')  =  x * y' <  x' * y
225
226 instance  (Integral a)  => Num (Ratio a)  where
227     {-# SPECIALIZE instance Num Rational #-}
228     (x:%y) + (x':%y')   =  reduce (x*y' + x'*y) (y*y')
229     (x:%y) - (x':%y')   =  reduce (x*y' - x'*y) (y*y')
230     (x:%y) * (x':%y')   =  reduce (x * x') (y * y')
231     negate (x:%y)       =  (-x) :% y
232     abs (x:%y)          =  abs x :% y
233     signum (x:%_)       =  signum x :% 1
234     fromInteger x       =  fromInteger x :% 1
235
236 instance  (Integral a)  => Fractional (Ratio a)  where
237     {-# SPECIALIZE instance Fractional Rational #-}
238     (x:%y) / (x':%y')   =  (x*y') % (y*x')
239     recip (x:%y)        =  y % x
240     fromRational (x:%y) =  fromInteger x :% fromInteger y
241
242 instance  (Integral a)  => Real (Ratio a)  where
243     {-# SPECIALIZE instance Real Rational #-}
244     toRational (x:%y)   =  toInteger x :% toInteger y
245
246 instance  (Integral a)  => RealFrac (Ratio a)  where
247     {-# SPECIALIZE instance RealFrac Rational #-}
248     properFraction (x:%y) = (fromInteger (toInteger q), r:%y)
249                           where (q,r) = quotRem x y
250
251 instance  (Integral a)  => Show (Ratio a)  where
252     {-# SPECIALIZE instance Show Rational #-}
253     showsPrec p (x:%y)  =  showParen (p > ratioPrec) $
254                            showsPrec ratioPrec1 x . 
255                            showString " % " . 
256                            showsPrec ratioPrec1 y
257
258 instance  (Integral a)  => Enum (Ratio a)  where
259     {-# SPECIALIZE instance Enum Rational #-}
260     succ x              =  x + 1
261     pred x              =  x - 1
262
263     toEnum n            =  fromInteger (int2Integer n) :% 1
264     fromEnum            =  fromInteger . truncate
265
266     enumFrom            =  numericEnumFrom
267     enumFromThen        =  numericEnumFromThen
268     enumFromTo          =  numericEnumFromTo
269     enumFromThenTo      =  numericEnumFromThenTo
270 \end{code}
271
272
273 %*********************************************************
274 %*                                                      *
275 \subsection{Coercions}
276 %*                                                      *
277 %*********************************************************
278
279 \begin{code}
280 fromIntegral :: (Integral a, Num b) => a -> b
281 fromIntegral = fromInteger . toInteger
282
283 {-# RULES
284 "fromIntegral/Int->Int" fromIntegral = id :: Int -> Int
285     #-}
286
287 realToFrac :: (Real a, Fractional b) => a -> b
288 realToFrac = fromRational . toRational
289
290 {-# RULES
291 "realToFrac/Int->Int" realToFrac = id :: Int -> Int
292     #-}
293 \end{code}
294
295 %*********************************************************
296 %*                                                      *
297 \subsection{Overloaded numeric functions}
298 %*                                                      *
299 %*********************************************************
300
301 \begin{code}
302 showSigned :: (Real a) => (a -> ShowS) -> Int -> a -> ShowS
303 showSigned showPos p x 
304    | x < 0     = showParen (p > 6) (showChar '-' . showPos (-x))
305    | otherwise = showPos x
306
307 even, odd       :: (Integral a) => a -> Bool
308 even n          =  n `rem` 2 == 0
309 odd             =  not . even
310
311 -------------------------------------------------------
312 {-# SPECIALISE (^) ::
313         Integer -> Integer -> Integer,
314         Integer -> Int -> Integer,
315         Int -> Int -> Int #-}
316 (^)             :: (Num a, Integral b) => a -> b -> a
317 _ ^ 0           =  1
318 x ^ n | n > 0   =  f x (n-1) x
319                    where f _ 0 y = y
320                          f a d y = g a d  where
321                                    g b i | even i  = g (b*b) (i `quot` 2)
322                                          | otherwise = f b (i-1) (b*y)
323 _ ^ _           = error "Prelude.^: negative exponent"
324
325 {-# SPECIALISE (^^) ::
326         Rational -> Int -> Rational #-}
327 (^^)            :: (Fractional a, Integral b) => a -> b -> a
328 x ^^ n          =  if n >= 0 then x^n else recip (x^(negate n))
329
330
331 -------------------------------------------------------
332 gcd             :: (Integral a) => a -> a -> a
333 gcd 0 0         =  error "Prelude.gcd: gcd 0 0 is undefined"
334 gcd x y         =  gcd' (abs x) (abs y)
335                    where gcd' a 0  =  a
336                          gcd' a b  =  gcd' b (a `rem` b)
337
338 lcm             :: (Integral a) => a -> a -> a
339 {-# SPECIALISE lcm :: Int -> Int -> Int #-}
340 lcm _ 0         =  0
341 lcm 0 _         =  0
342 lcm x y         =  abs ((x `quot` (gcd x y)) * y)
343
344
345 {-# RULES
346 "gcd/Int->Int->Int"             gcd = gcdInt
347 "gcd/Integer->Integer->Integer" gcd = gcdInteger
348 "lcm/Integer->Integer->Integer" lcm = lcmInteger
349  #-}
350
351 integralEnumFrom :: (Integral a, Bounded a) => a -> [a]
352 integralEnumFrom n = map fromInteger [toInteger n .. toInteger (maxBound `asTypeOf` n)]
353
354 integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a]
355 integralEnumFromThen n1 n2
356   | i_n2 >= i_n1  = map fromInteger [i_n1, i_n2 .. toInteger (maxBound `asTypeOf` n1)]
357   | otherwise     = map fromInteger [i_n1, i_n2 .. toInteger (minBound `asTypeOf` n1)]
358   where
359     i_n1 = toInteger n1
360     i_n2 = toInteger n2
361
362 integralEnumFromTo :: Integral a => a -> a -> [a]
363 integralEnumFromTo n m = map fromInteger [toInteger n .. toInteger m]
364
365 integralEnumFromThenTo :: Integral a => a -> a -> a -> [a]
366 integralEnumFromThenTo n1 n2 m
367   = map fromInteger [toInteger n1, toInteger n2 .. toInteger m]
368 \end{code}