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