9a81c90a335f2f6c5c49ffc9e2746c8886d8d5e8
[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     {-# INLINE (-) #-}
79     {-# INLINE negate #-}
80     x - y               = x + negate y
81     negate x            = 0 - x
82
83 -- | the same as @'flip' ('-')@.
84 --
85 -- Because @-@ is treated specially in the Haskell grammar,
86 -- @(-@ /e/@)@ is not a section, but an application of prefix negation.
87 -- However, @('subtract'@ /exp/@)@ is equivalent to the disallowed section.
88 {-# INLINE subtract #-}
89 subtract :: (Num a) => a -> a -> a
90 subtract x y = y - x
91 \end{code}
92
93
94 %*********************************************************
95 %*                                                      *
96 \subsection{Instances for @Int@}
97 %*                                                      *
98 %*********************************************************
99
100 \begin{code}
101 instance  Num Int  where
102     (+)    = plusInt
103     (-)    = minusInt
104     negate = negateInt
105     (*)    = timesInt
106     abs n  = if n `geInt` 0 then n else negateInt n
107
108     signum n | n `ltInt` 0 = negateInt 1
109              | n `eqInt` 0 = 0
110              | otherwise   = 1
111
112     fromInteger i = I# (toInt# i)
113
114 quotRemInt :: Int -> Int -> (Int, Int)
115 quotRemInt a@(I# _) b@(I# _) = (a `quotInt` b, a `remInt` b)
116     -- OK, so I made it a little stricter.  Shoot me.  (WDP 94/10)
117
118 divModInt ::  Int -> Int -> (Int, Int)
119 divModInt x@(I# _) y@(I# _) = (x `divInt` y, x `modInt` y)
120     -- Stricter.  Sorry if you don't like it.  (WDP 94/10)
121 \end{code}
122
123 %*********************************************************
124 %*                                                      *
125 \subsection{The @Integer@ instances for @Show@}
126 %*                                                      *
127 %*********************************************************
128
129 \begin{code}
130 instance Show Integer where
131     showsPrec p n r
132         | p > 6 && n < 0 = '(' : integerToString n (')' : r)
133         -- Minor point: testing p first gives better code
134         -- in the not-uncommon case where the p argument
135         -- is a constant
136         | otherwise = integerToString n r
137     showList = showList__ (showsPrec 0)
138
139 -- Divide an conquer implementation of string conversion
140 integerToString :: Integer -> String -> String
141 integerToString n0 cs0
142     | n0 < 0    = '-' : integerToString' (- n0) cs0
143     | otherwise = integerToString' n0 cs0
144     where
145     integerToString' :: Integer -> String -> String
146     integerToString' n cs
147         | n < BASE  = jhead (fromInteger n) cs
148         | otherwise = jprinth (jsplitf (BASE*BASE) n) cs
149
150     -- Split n into digits in base p. We first split n into digits
151     -- in base p*p and then split each of these digits into two.
152     -- Note that the first 'digit' modulo p*p may have a leading zero
153     -- in base p that we need to drop - this is what jsplith takes care of.
154     -- jsplitb the handles the remaining digits.
155     jsplitf :: Integer -> Integer -> [Integer]
156     jsplitf p n
157         | p > n     = [n]
158         | otherwise = jsplith p (jsplitf (p*p) n)
159
160     jsplith :: Integer -> [Integer] -> [Integer]
161     jsplith p (n:ns) =
162         case n `quotRemInteger` p of
163         (# q, r #) ->
164             if q > 0 then q : r : jsplitb p ns
165                      else     r : jsplitb p ns
166     jsplith _ [] = error "jsplith: []"
167
168     jsplitb :: Integer -> [Integer] -> [Integer]
169     jsplitb _ []     = []
170     jsplitb p (n:ns) = case n `quotRemInteger` p of
171                        (# q, r #) ->
172                            q : r : jsplitb p ns
173
174     -- Convert a number that has been split into digits in base BASE^2
175     -- this includes a last splitting step and then conversion of digits
176     -- that all fit into a machine word.
177     jprinth :: [Integer] -> String -> String
178     jprinth (n:ns) cs =
179         case n `quotRemInteger` BASE of
180         (# q', r' #) ->
181             let q = fromInteger q'
182                 r = fromInteger r'
183             in if q > 0 then jhead q $ jblock r $ jprintb ns cs
184                         else jhead r $ jprintb ns cs
185     jprinth [] _ = error "jprinth []"
186
187     jprintb :: [Integer] -> String -> String
188     jprintb []     cs = cs
189     jprintb (n:ns) cs = case n `quotRemInteger` BASE of
190                         (# q', r' #) ->
191                             let q = fromInteger q'
192                                 r = fromInteger r'
193                             in jblock q $ jblock r $ jprintb ns cs
194
195     -- Convert an integer that fits into a machine word. Again, we have two
196     -- functions, one that drops leading zeros (jhead) and one that doesn't
197     -- (jblock)
198     jhead :: Int -> String -> String
199     jhead n cs
200         | n < 10    = case unsafeChr (ord '0' + n) of
201             c@(C# _) -> c : cs
202         | otherwise = case unsafeChr (ord '0' + r) of
203             c@(C# _) -> jhead q (c : cs)
204         where
205         (q, r) = n `quotRemInt` 10
206
207     jblock = jblock' {- ' -} DIGITS
208
209     jblock' :: Int -> Int -> String -> String
210     jblock' d n cs
211         | d == 1    = case unsafeChr (ord '0' + n) of
212              c@(C# _) -> c : cs
213         | otherwise = case unsafeChr (ord '0' + r) of
214              c@(C# _) -> jblock' (d - 1) q (c : cs)
215         where
216         (q, r) = n `quotRemInt` 10
217 \end{code}
218
219
220 %*********************************************************
221 %*                                                      *
222 \subsection{The @Integer@ instances for @Num@}
223 %*                                                      *
224 %*********************************************************
225
226 \begin{code}
227 instance  Num Integer  where
228     (+) = plusInteger
229     (-) = minusInteger
230     (*) = timesInteger
231     negate         = negateInteger
232     fromInteger x  =  x
233
234     abs = absInteger
235     signum = signumInteger
236 \end{code}
237
238
239 %*********************************************************
240 %*                                                      *
241 \subsection{The @Integer@ instance for @Enum@}
242 %*                                                      *
243 %*********************************************************
244
245 \begin{code}
246 instance  Enum Integer  where
247     succ x               = x + 1
248     pred x               = x - 1
249     toEnum (I# n)        = smallInteger n
250     fromEnum n           = I# (toInt# n)
251
252     {-# INLINE enumFrom #-}
253     {-# INLINE enumFromThen #-}
254     {-# INLINE enumFromTo #-}
255     {-# INLINE enumFromThenTo #-}
256     enumFrom x             = enumDeltaInteger  x 1
257     enumFromThen x y       = enumDeltaInteger  x (y-x)
258     enumFromTo x lim       = enumDeltaToInteger x 1     lim
259     enumFromThenTo x y lim = enumDeltaToInteger x (y-x) lim
260
261 {-# RULES
262 "enumDeltaInteger"      [~1] forall x y.  enumDeltaInteger x y     = build (\c _ -> enumDeltaIntegerFB c x y)
263 "efdtInteger"           [~1] forall x y l.enumDeltaToInteger x y l = build (\c n -> enumDeltaToIntegerFB c n x y l)
264 "enumDeltaInteger"      [1] enumDeltaIntegerFB   (:)    = enumDeltaInteger
265 "enumDeltaToInteger"    [1] enumDeltaToIntegerFB (:) [] = enumDeltaToInteger
266  #-}
267
268 enumDeltaIntegerFB :: (Integer -> b -> b) -> Integer -> Integer -> b
269 enumDeltaIntegerFB c x d = x `seq` (x `c` enumDeltaIntegerFB c (x+d) d)
270
271 enumDeltaInteger :: Integer -> Integer -> [Integer]
272 enumDeltaInteger x d = x `seq` (x : enumDeltaInteger (x+d) d)
273 -- strict accumulator, so
274 --     head (drop 1000000 [1 .. ]
275 -- works
276
277 {-# NOINLINE [0] enumDeltaToIntegerFB #-}
278 -- Don't inline this until RULE "enumDeltaToInteger" has had a chance to fire
279 enumDeltaToIntegerFB :: (Integer -> a -> a) -> a
280                      -> Integer -> Integer -> Integer -> a
281 enumDeltaToIntegerFB c n x delta lim
282   | delta >= 0 = up_fb c n x delta lim
283   | otherwise  = dn_fb c n x delta lim
284
285 enumDeltaToInteger :: Integer -> Integer -> Integer -> [Integer]
286 enumDeltaToInteger x delta lim
287   | delta >= 0 = up_list x delta lim
288   | otherwise  = dn_list x delta lim
289
290 up_fb :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a
291 up_fb c n x0 delta lim = go (x0 :: Integer)
292                       where
293                         go x | x > lim   = n
294                              | otherwise = x `c` go (x+delta)
295 dn_fb :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a
296 dn_fb c n x0 delta lim = go (x0 :: Integer)
297                       where
298                         go x | x < lim   = n
299                              | otherwise = x `c` go (x+delta)
300
301 up_list :: Integer -> Integer -> Integer -> [Integer]
302 up_list x0 delta lim = go (x0 :: Integer)
303                     where
304                         go x | x > lim   = []
305                              | otherwise = x : go (x+delta)
306 dn_list :: Integer -> Integer -> Integer -> [Integer]
307 dn_list x0 delta lim = go (x0 :: Integer)
308                     where
309                         go x | x < lim   = []
310                              | otherwise = x : go (x+delta)
311 \end{code}
312