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