Move Integer out into its own package
[ghc-base.git] / GHC / Num.lhs
1 \begin{code}
2 {-# OPTIONS_GHC -fno-implicit-prelude #-}
3 {-# OPTIONS_HADDOCK hide #-}
4 -----------------------------------------------------------------------------
5 -- |
6 -- Module      :  GHC.Num
7 -- Copyright   :  (c) The University of Glasgow 1994-2002
8 -- License     :  see libraries/base/LICENSE
9 -- 
10 -- Maintainer  :  cvs-ghc@haskell.org
11 -- Stability   :  internal
12 -- Portability :  non-portable (GHC Extensions)
13 --
14 -- The 'Num' class and the 'Integer' type.
15 --
16 -----------------------------------------------------------------------------
17
18 #include "MachDeps.h"
19 #if SIZEOF_HSWORD == 4
20 #define DIGITS       9
21 #define BASE         1000000000
22 #elif SIZEOF_HSWORD == 8
23 #define DIGITS       18
24 #define BASE         1000000000000000000
25 #else
26 #error Please define DIGITS and BASE
27 -- DIGITS should be the largest integer such that
28 --     10^DIGITS < 2^(SIZEOF_HSWORD * 8 - 1)
29 -- BASE should be 10^DIGITS. Note that ^ is not available yet.
30 #endif
31
32 -- #hide
33 module GHC.Num (module GHC.Num, module GHC.Integer) where
34
35 import GHC.Base
36 import GHC.Enum
37 import GHC.Show
38 import GHC.Integer
39
40 infixl 7  *
41 infixl 6  +, -
42
43 default ()              -- Double isn't available yet, 
44                         -- and we shouldn't be using defaults anyway
45 \end{code}
46
47 %*********************************************************
48 %*                                                      *
49 \subsection{Standard numeric class}
50 %*                                                      *
51 %*********************************************************
52
53 \begin{code}
54 -- | Basic numeric class.
55 --
56 -- Minimal complete definition: all except 'negate' or @(-)@
57 class  (Eq a, Show a) => Num a  where
58     (+), (-), (*)       :: a -> a -> a
59     -- | Unary negation.
60     negate              :: a -> a
61     -- | Absolute value.
62     abs                 :: a -> a
63     -- | Sign of a number.
64     -- The functions 'abs' and 'signum' should satisfy the law: 
65     --
66     -- > abs x * signum x == x
67     --
68     -- For real numbers, the 'signum' is either @-1@ (negative), @0@ (zero)
69     -- or @1@ (positive).
70     signum              :: a -> a
71     -- | Conversion from an 'Integer'.
72     -- An integer literal represents the application of the function
73     -- 'fromInteger' to the appropriate value of type 'Integer',
74     -- so such literals have type @('Num' a) => a@.
75     fromInteger         :: Integer -> a
76
77     x - y               = x + negate y
78     negate x            = 0 - x
79
80 -- | the same as @'flip' ('-')@.
81 --
82 -- Because @-@ is treated specially in the Haskell grammar,
83 -- @(-@ /e/@)@ is not a section, but an application of prefix negation.
84 -- However, @('subtract'@ /exp/@)@ is equivalent to the disallowed section.
85 {-# INLINE subtract #-}
86 subtract :: (Num a) => a -> a -> a
87 subtract x y = y - x
88 \end{code}
89
90
91 %*********************************************************
92 %*                                                      *
93 \subsection{Instances for @Int@}
94 %*                                                      *
95 %*********************************************************
96
97 \begin{code}
98 instance  Num Int  where
99     (+)    = plusInt
100     (-)    = minusInt
101     negate = negateInt
102     (*)    = timesInt
103     abs n  = if n `geInt` 0 then n else negateInt n
104
105     signum n | n `ltInt` 0 = negateInt 1
106              | n `eqInt` 0 = 0
107              | otherwise   = 1
108
109     fromInteger i = I# (toInt# i)
110
111 quotRemInt :: Int -> Int -> (Int, Int)
112 quotRemInt a@(I# _) b@(I# _) = (a `quotInt` b, a `remInt` b)
113     -- OK, so I made it a little stricter.  Shoot me.  (WDP 94/10)
114
115 divModInt ::  Int -> Int -> (Int, Int)
116 divModInt x@(I# _) y@(I# _) = (x `divInt` y, x `modInt` y)
117     -- Stricter.  Sorry if you don't like it.  (WDP 94/10)
118 \end{code}
119
120 %*********************************************************
121 %*                                                      *
122 \subsection{The @Integer@ instances for @Eq@, @Ord@}
123 %*                                                      *
124 %*********************************************************
125
126 \begin{code}
127 instance  Eq Integer  where
128     (==) = eqInteger
129     (/=) = neqInteger
130
131 ------------------------------------------------------------------------
132 instance Ord Integer where
133     (<=) = leInteger
134     (>)  = gtInteger
135     (<)  = ltInteger
136     (>=) = geInteger
137
138     i `compare` j = case i `compareInteger` j of
139                     -1# -> LT
140                     0#  -> EQ
141                     1#  -> GT
142                     _   -> error "compareInteger: Bad result"
143 \end{code}
144
145
146 %*********************************************************
147 %*                                                      *
148 \subsection{The @Integer@ instances for @Show@}
149 %*                                                      *
150 %*********************************************************
151
152 \begin{code}
153 instance Show Integer where
154     showsPrec p n r
155         | p > 6 && n < 0 = '(' : integerToString n (')' : r)
156         -- Minor point: testing p first gives better code
157         -- in the not-uncommon case where the p argument
158         -- is a constant
159         | otherwise = integerToString n r
160     showList = showList__ (showsPrec 0)
161
162 -- Divide an conquer implementation of string conversion
163 integerToString :: Integer -> String -> String
164 integerToString n cs
165     | n < 0     = '-' : integerToString' (-n) cs
166     | otherwise = integerToString' n cs
167     where
168     integerToString' :: Integer -> String -> String
169     integerToString' n cs
170         | n < BASE  = jhead (fromInteger n) cs
171         | otherwise = jprinth (jsplitf (BASE*BASE) n) cs
172
173     -- Split n into digits in base p. We first split n into digits
174     -- in base p*p and then split each of these digits into two.
175     -- Note that the first 'digit' modulo p*p may have a leading zero
176     -- in base p that we need to drop - this is what jsplith takes care of.
177     -- jsplitb the handles the remaining digits.
178     jsplitf :: Integer -> Integer -> [Integer]
179     jsplitf p n
180         | p > n     = [n]
181         | otherwise = jsplith p (jsplitf (p*p) n)
182
183     jsplith :: Integer -> [Integer] -> [Integer]
184     jsplith p (n:ns) =
185         case n `quotRemInteger` p of
186         (# q, r #) ->
187             if q > 0 then fromInteger q : fromInteger r : jsplitb p ns
188                      else fromInteger r : jsplitb p ns
189
190     jsplitb :: Integer -> [Integer] -> [Integer]
191     jsplitb p []     = []
192     jsplitb p (n:ns) = case n `quotRemInteger` p of
193                        (# q, r #) ->
194                            q : r : jsplitb p ns
195
196     -- Convert a number that has been split into digits in base BASE^2
197     -- this includes a last splitting step and then conversion of digits
198     -- that all fit into a machine word.
199     jprinth :: [Integer] -> String -> String
200     jprinth (n:ns) cs =
201         case n `quotRemInteger` BASE of
202         (# q', r' #) ->
203             let q = fromInteger q'
204                 r = fromInteger r'
205             in if q > 0 then jhead q $ jblock r $ jprintb ns cs
206                         else jhead r $ jprintb ns cs
207
208     jprintb :: [Integer] -> String -> String
209     jprintb []     cs = cs
210     jprintb (n:ns) cs = case n `quotRemInteger` BASE of
211                         (# q', r' #) ->
212                             let q = fromInteger q'
213                                 r = fromInteger r'
214                             in jblock q $ jblock r $ jprintb ns cs
215
216     -- Convert an integer that fits into a machine word. Again, we have two
217     -- functions, one that drops leading zeros (jhead) and one that doesn't
218     -- (jblock)
219     jhead :: Int -> String -> String
220     jhead n cs
221         | n < 10    = case unsafeChr (ord '0' + n) of
222             c@(C# _) -> c : cs
223         | otherwise = case unsafeChr (ord '0' + r) of
224             c@(C# _) -> jhead q (c : cs)
225         where
226         (q, r) = n `quotRemInt` 10
227
228     jblock = jblock' {- ' -} DIGITS
229
230     jblock' :: Int -> Int -> String -> String
231     jblock' d n cs
232         | d == 1    = case unsafeChr (ord '0' + n) of
233              c@(C# _) -> c : cs
234         | otherwise = case unsafeChr (ord '0' + r) of
235              c@(C# _) -> jblock' (d - 1) q (c : cs)
236         where
237         (q, r) = n `quotRemInt` 10
238 \end{code}
239
240
241 %*********************************************************
242 %*                                                      *
243 \subsection{The @Integer@ instances for @Num@}
244 %*                                                      *
245 %*********************************************************
246
247 \begin{code}
248 instance  Num Integer  where
249     (+) = plusInteger
250     (-) = minusInteger
251     (*) = timesInteger
252     negate         = negateInteger
253     fromInteger x  =  x
254
255     abs = absInteger
256     signum = signumInteger
257 \end{code}
258
259
260 %*********************************************************
261 %*                                                      *
262 \subsection{The @Integer@ instance for @Enum@}
263 %*                                                      *
264 %*********************************************************
265
266 \begin{code}
267 instance  Enum Integer  where
268     succ x               = x + 1
269     pred x               = x - 1
270     toEnum (I# n)        = smallInteger n
271     fromEnum n           = I# (toInt# n)
272
273     {-# INLINE enumFrom #-}
274     {-# INLINE enumFromThen #-}
275     {-# INLINE enumFromTo #-}
276     {-# INLINE enumFromThenTo #-}
277     enumFrom x             = enumDeltaInteger  x 1
278     enumFromThen x y       = enumDeltaInteger  x (y-x)
279     enumFromTo x lim       = enumDeltaToInteger x 1     lim
280     enumFromThenTo x y lim = enumDeltaToInteger x (y-x) lim
281
282 {-# RULES
283 "enumDeltaInteger"      [~1] forall x y.  enumDeltaInteger x y     = build (\c _ -> enumDeltaIntegerFB c x y)
284 "efdtInteger"           [~1] forall x y l.enumDeltaToInteger x y l = build (\c n -> enumDeltaToIntegerFB c n x y l)
285 "enumDeltaInteger"      [1] enumDeltaIntegerFB   (:)    = enumDeltaInteger
286 "enumDeltaToInteger"    [1] enumDeltaToIntegerFB (:) [] = enumDeltaToInteger
287  #-}
288
289 enumDeltaIntegerFB :: (Integer -> b -> b) -> Integer -> Integer -> b
290 enumDeltaIntegerFB c x d = x `c` enumDeltaIntegerFB c (x+d) d
291
292 enumDeltaInteger :: Integer -> Integer -> [Integer]
293 enumDeltaInteger x d = x : enumDeltaInteger (x+d) d
294
295 enumDeltaToIntegerFB c n x delta lim
296   | delta >= 0 = up_fb c n x delta lim
297   | otherwise  = dn_fb c n x delta lim
298
299 enumDeltaToInteger x delta lim
300   | delta >= 0 = up_list x delta lim
301   | otherwise  = dn_list x delta lim
302
303 up_fb c n x delta lim = go (x::Integer)
304                       where
305                         go x | x > lim   = n
306                              | otherwise = x `c` go (x+delta)
307 dn_fb c n x delta lim = go (x::Integer)
308                       where
309                         go x | x < lim   = n
310                              | otherwise = x `c` go (x+delta)
311
312 up_list x delta lim = go (x::Integer)
313                     where
314                         go x | x > lim   = []
315                              | otherwise = x : go (x+delta)
316 dn_list x delta lim = go (x::Integer)
317                     where
318                         go x | x < lim   = []
319                              | otherwise = x : go (x+delta)
320
321 \end{code}
322