1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
|
\begin{code}
{-# OPTIONS -fno-implicit-prelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Real
-- Copyright : (c) The FFI Task Force, 1994-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : cvs-ghc@haskell.org
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- The types 'Ratio' and 'Rational', and the classes 'Real', 'Fractional',
-- 'Integral', and 'RealFrac'.
--
-----------------------------------------------------------------------------
module GHC.Real where
import {-# SOURCE #-} GHC.Err
import GHC.Base
import GHC.Num
import GHC.List
import GHC.Enum
import GHC.Show
infixr 8 ^, ^^
infixl 7 /, `quot`, `rem`, `div`, `mod`
infixl 7 %
default () -- Double isn't available yet,
-- and we shouldn't be using defaults anyway
\end{code}
%*********************************************************
%* *
\subsection{The @Ratio@ and @Rational@ types}
%* *
%*********************************************************
\begin{code}
-- | Rational numbers, with numerator and denominator of some 'Integral' type.
data (Integral a) => Ratio a = !a :% !a deriving (Eq)
-- | Arbitrary-precision rational numbers, represented as a ratio of
-- two 'Integer' values. A rational number may be constructed using
-- the '%' operator.
type Rational = Ratio Integer
ratioPrec, ratioPrec1 :: Int
ratioPrec = 7 -- Precedence of ':%' constructor
ratioPrec1 = ratioPrec + 1
infinity, notANumber :: Rational
infinity = 1 :% 0
notANumber = 0 :% 0
-- Use :%, not % for Inf/NaN; the latter would
-- immediately lead to a runtime error, because it normalises.
\end{code}
\begin{code}
-- | Forms the ratio of two integral numbers.
{-# SPECIALISE (%) :: Integer -> Integer -> Rational #-}
(%) :: (Integral a) => a -> a -> Ratio a
-- | Extract the numerator of the ratio in reduced form:
-- the numerator and denominator have no common factor and the denominator
-- is positive.
numerator :: (Integral a) => Ratio a -> a
-- | Extract the denominator of the ratio in reduced form:
-- the numerator and denominator have no common factor and the denominator
-- is positive.
denominator :: (Integral a) => Ratio a -> a
\end{code}
\tr{reduce} is a subsidiary function used only in this module .
It normalises a ratio by dividing both numerator and denominator by
their greatest common divisor.
\begin{code}
reduce :: (Integral a) => a -> a -> Ratio a
{-# SPECIALISE reduce :: Integer -> Integer -> Rational #-}
reduce _ 0 = error "Ratio.%: zero denominator"
reduce x y = (x `quot` d) :% (y `quot` d)
where d = gcd x y
\end{code}
\begin{code}
x % y = reduce (x * signum y) (abs y)
numerator (x :% _) = x
denominator (_ :% y) = y
\end{code}
%*********************************************************
%* *
\subsection{Standard numeric classes}
%* *
%*********************************************************
\begin{code}
class (Num a, Ord a) => Real a where
-- | the rational equivalent of its real argument with full precision
toRational :: a -> Rational
-- | Integral numbers, supporting integer division.
--
-- Minimal complete definition: 'quotRem' and 'toInteger'
class (Real a, Enum a) => Integral a where
-- | integer division truncated toward zero
quot :: a -> a -> a
-- | integer remainder, satisfying
--
-- > (x `quot` y)*y + (x `rem` y) == x
rem :: a -> a -> a
-- | integer division truncated toward negative infinity
div :: a -> a -> a
-- | integer modulus, satisfying
--
-- > (x `div` y)*y + (x `mod` y) == x
mod :: a -> a -> a
-- | simultaneous 'quot' and 'rem'
quotRem :: a -> a -> (a,a)
-- | simultaneous 'div' and 'mod'
divMod :: a -> a -> (a,a)
-- | conversion to 'Integer'
toInteger :: a -> Integer
n `quot` d = q where (q,_) = quotRem n d
n `rem` d = r where (_,r) = quotRem n d
n `div` d = q where (q,_) = divMod n d
n `mod` d = r where (_,r) = divMod n d
divMod n d = if signum r == negate (signum d) then (q-1, r+d) else qr
where qr@(q,r) = quotRem n d
-- | Fractional numbers, supporting real division.
--
-- Minimal complete definition: 'fromRational' and ('recip' or @('/')@)
class (Num a) => Fractional a where
-- | fractional division
(/) :: a -> a -> a
-- | reciprocal fraction
recip :: a -> a
-- | Conversion from a 'Rational' (that is @'Ratio' 'Integer'@).
-- A floating literal stands for an application of 'fromRational'
-- to a value of type 'Rational', so such literals have type
-- @('Fractional' a) => a@.
fromRational :: Rational -> a
recip x = 1 / x
x / y = x * recip y
-- | Extracting components of fractions.
--
-- Minimal complete definition: 'properFraction'
class (Real a, Fractional a) => RealFrac a where
-- | The function 'properFraction' takes a real fractional number @x@
-- and returns a pair @(n,f)@ such that @x = n+f@, and:
--
-- * @n@ is an integral number with the same sign as @x@; and
--
-- * @f@ is a fraction with the same type and sign as @x@,
-- and with absolute value less than @1@.
--
-- The default definitions of the 'ceiling', 'floor', 'truncate'
-- and 'round' functions are in terms of 'properFraction'.
properFraction :: (Integral b) => a -> (b,a)
-- | @'truncate' x@ returns the integer nearest @x@ between zero and @x@
truncate :: (Integral b) => a -> b
-- | @'round' x@ returns the nearest integer to @x@
round :: (Integral b) => a -> b
-- | @'ceiling' x@ returns the least integer not less than @x@
ceiling :: (Integral b) => a -> b
-- | @'floor' x@ returns the greatest integer not greater than @x@
floor :: (Integral b) => a -> b
truncate x = m where (m,_) = properFraction x
round x = let (n,r) = properFraction x
m = if r < 0 then n - 1 else n + 1
in case signum (abs r - 0.5) of
-1 -> n
0 -> if even n then n else m
1 -> m
ceiling x = if r > 0 then n + 1 else n
where (n,r) = properFraction x
floor x = if r < 0 then n - 1 else n
where (n,r) = properFraction x
\end{code}
These 'numeric' enumerations come straight from the Report
\begin{code}
numericEnumFrom :: (Fractional a) => a -> [a]
numericEnumFrom = iterate (+1)
numericEnumFromThen :: (Fractional a) => a -> a -> [a]
numericEnumFromThen n m = iterate (+(m-n)) n
numericEnumFromTo :: (Ord a, Fractional a) => a -> a -> [a]
numericEnumFromTo n m = takeWhile (<= m + 1/2) (numericEnumFrom n)
numericEnumFromThenTo :: (Ord a, Fractional a) => a -> a -> a -> [a]
numericEnumFromThenTo e1 e2 e3 = takeWhile pred (numericEnumFromThen e1 e2)
where
mid = (e2 - e1) / 2
pred | e2 >= e1 = (<= e3 + mid)
| otherwise = (>= e3 + mid)
\end{code}
%*********************************************************
%* *
\subsection{Instances for @Int@}
%* *
%*********************************************************
\begin{code}
instance Real Int where
toRational x = toInteger x % 1
instance Integral Int where
toInteger i = int2Integer i -- give back a full-blown Integer
a `quot` 0 = divZeroError
a `quot` b = a `quotInt` b
a `rem` 0 = divZeroError
a `rem` b = a `remInt` b
a `div` 0 = divZeroError
a `div` b = a `divInt` b
a `mod` 0 = divZeroError
a `mod` b = a `modInt` b
a `quotRem` 0 = divZeroError
a `quotRem` b = a `quotRemInt` b
a `divMod` 0 = divZeroError
a `divMod` b = a `divModInt` b
\end{code}
%*********************************************************
%* *
\subsection{Instances for @Integer@}
%* *
%*********************************************************
\begin{code}
instance Real Integer where
toRational x = x % 1
instance Integral Integer where
toInteger n = n
a `quot` 0 = divZeroError
n `quot` d = n `quotInteger` d
a `rem` 0 = divZeroError
n `rem` d = n `remInteger` d
a `divMod` 0 = divZeroError
a `divMod` b = a `divModInteger` b
a `quotRem` 0 = divZeroError
a `quotRem` b = a `quotRemInteger` b
-- use the defaults for div & mod
\end{code}
%*********************************************************
%* *
\subsection{Instances for @Ratio@}
%* *
%*********************************************************
\begin{code}
instance (Integral a) => Ord (Ratio a) where
{-# SPECIALIZE instance Ord Rational #-}
(x:%y) <= (x':%y') = x * y' <= x' * y
(x:%y) < (x':%y') = x * y' < x' * y
instance (Integral a) => Num (Ratio a) where
{-# SPECIALIZE instance Num Rational #-}
(x:%y) + (x':%y') = reduce (x*y' + x'*y) (y*y')
(x:%y) - (x':%y') = reduce (x*y' - x'*y) (y*y')
(x:%y) * (x':%y') = reduce (x * x') (y * y')
negate (x:%y) = (-x) :% y
abs (x:%y) = abs x :% y
signum (x:%_) = signum x :% 1
fromInteger x = fromInteger x :% 1
instance (Integral a) => Fractional (Ratio a) where
{-# SPECIALIZE instance Fractional Rational #-}
(x:%y) / (x':%y') = (x*y') % (y*x')
recip (x:%y) = y % x
fromRational (x:%y) = fromInteger x :% fromInteger y
instance (Integral a) => Real (Ratio a) where
{-# SPECIALIZE instance Real Rational #-}
toRational (x:%y) = toInteger x :% toInteger y
instance (Integral a) => RealFrac (Ratio a) where
{-# SPECIALIZE instance RealFrac Rational #-}
properFraction (x:%y) = (fromInteger (toInteger q), r:%y)
where (q,r) = quotRem x y
instance (Integral a) => Show (Ratio a) where
{-# SPECIALIZE instance Show Rational #-}
showsPrec p (x:%y) = showParen (p > ratioPrec) $
showsPrec ratioPrec1 x .
showString "%" . -- H98 report has spaces round the %
-- but we removed them [May 04]
showsPrec ratioPrec1 y
instance (Integral a) => Enum (Ratio a) where
{-# SPECIALIZE instance Enum Rational #-}
succ x = x + 1
pred x = x - 1
toEnum n = fromInteger (int2Integer n) :% 1
fromEnum = fromInteger . truncate
enumFrom = numericEnumFrom
enumFromThen = numericEnumFromThen
enumFromTo = numericEnumFromTo
enumFromThenTo = numericEnumFromThenTo
\end{code}
%*********************************************************
%* *
\subsection{Coercions}
%* *
%*********************************************************
\begin{code}
-- | general coercion from integral types
fromIntegral :: (Integral a, Num b) => a -> b
fromIntegral = fromInteger . toInteger
{-# RULES
"fromIntegral/Int->Int" fromIntegral = id :: Int -> Int
#-}
-- | general coercion to fractional types
realToFrac :: (Real a, Fractional b) => a -> b
realToFrac = fromRational . toRational
{-# RULES
"realToFrac/Int->Int" realToFrac = id :: Int -> Int
#-}
\end{code}
%*********************************************************
%* *
\subsection{Overloaded numeric functions}
%* *
%*********************************************************
\begin{code}
-- | Converts a possibly-negative 'Real' value to a string.
showSigned :: (Real a)
=> (a -> ShowS) -- ^ a function that can show unsigned values
-> Int -- ^ the precedence of the enclosing context
-> a -- ^ the value to show
-> ShowS
showSigned showPos p x
| x < 0 = showParen (p > 6) (showChar '-' . showPos (-x))
| otherwise = showPos x
even, odd :: (Integral a) => a -> Bool
even n = n `rem` 2 == 0
odd = not . even
-------------------------------------------------------
-- | raise a number to a non-negative integral power
{-# SPECIALISE (^) ::
Integer -> Integer -> Integer,
Integer -> Int -> Integer,
Int -> Int -> Int #-}
(^) :: (Num a, Integral b) => a -> b -> a
_ ^ 0 = 1
x ^ n | n > 0 = f x (n-1) x
where f _ 0 y = y
f a d y = g a d where
g b i | even i = g (b*b) (i `quot` 2)
| otherwise = f b (i-1) (b*y)
_ ^ _ = error "Prelude.^: negative exponent"
-- | raise a number to an integral power
{-# SPECIALISE (^^) ::
Rational -> Int -> Rational #-}
(^^) :: (Fractional a, Integral b) => a -> b -> a
x ^^ n = if n >= 0 then x^n else recip (x^(negate n))
-------------------------------------------------------
-- | @'gcd' x y@ is the greatest (positive) integer that divides both @x@
-- and @y@; for example @'gcd' (-3) 6@ = @3@, @'gcd' (-3) (-6)@ = @3@,
-- @'gcd' 0 4@ = @4@. @'gcd' 0 0@ raises a runtime error.
gcd :: (Integral a) => a -> a -> a
gcd 0 0 = error "Prelude.gcd: gcd 0 0 is undefined"
gcd x y = gcd' (abs x) (abs y)
where gcd' a 0 = a
gcd' a b = gcd' b (a `rem` b)
-- | @'lcm' x y@ is the smallest positive integer that both @x@ and @y@ divide.
lcm :: (Integral a) => a -> a -> a
{-# SPECIALISE lcm :: Int -> Int -> Int #-}
lcm _ 0 = 0
lcm 0 _ = 0
lcm x y = abs ((x `quot` (gcd x y)) * y)
{-# RULES
"gcd/Int->Int->Int" gcd = gcdInt
"gcd/Integer->Integer->Integer" gcd = gcdInteger
"lcm/Integer->Integer->Integer" lcm = lcmInteger
#-}
integralEnumFrom :: (Integral a, Bounded a) => a -> [a]
integralEnumFrom n = map fromInteger [toInteger n .. toInteger (maxBound `asTypeOf` n)]
integralEnumFromThen :: (Integral a, Bounded a) => a -> a -> [a]
integralEnumFromThen n1 n2
| i_n2 >= i_n1 = map fromInteger [i_n1, i_n2 .. toInteger (maxBound `asTypeOf` n1)]
| otherwise = map fromInteger [i_n1, i_n2 .. toInteger (minBound `asTypeOf` n1)]
where
i_n1 = toInteger n1
i_n2 = toInteger n2
integralEnumFromTo :: Integral a => a -> a -> [a]
integralEnumFromTo n m = map fromInteger [toInteger n .. toInteger m]
integralEnumFromThenTo :: Integral a => a -> a -> a -> [a]
integralEnumFromThenTo n1 n2 m
= map fromInteger [toInteger n1, toInteger n2 .. toInteger m]
\end{code}
|