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