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