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