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