base: Manually unlit .lhs into .hs modules
[ghc.git] / libraries / base / GHC / Num.hs
1 {-# LANGUAGE Trustworthy #-}
2 {-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples #-}
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 module GHC.Num (module GHC.Num, module GHC.Integer) where
19
20 import GHC.Base
21 import GHC.Integer
22
23 infixl 7 *
24 infixl 6 +, -
25
26 default () -- Double isn't available yet,
27 -- and we shouldn't be using defaults anyway
28
29 -- | Basic numeric class.
30 class Num a where
31 {-# MINIMAL (+), (*), abs, signum, fromInteger, (negate | (-)) #-}
32
33 (+), (-), (*) :: a -> a -> a
34 -- | Unary negation.
35 negate :: a -> a
36 -- | Absolute value.
37 abs :: a -> a
38 -- | Sign of a number.
39 -- The functions 'abs' and 'signum' should satisfy the law:
40 --
41 -- > abs x * signum x == x
42 --
43 -- For real numbers, the 'signum' is either @-1@ (negative), @0@ (zero)
44 -- or @1@ (positive).
45 signum :: a -> a
46 -- | Conversion from an 'Integer'.
47 -- An integer literal represents the application of the function
48 -- 'fromInteger' to the appropriate value of type 'Integer',
49 -- so such literals have type @('Num' a) => a@.
50 fromInteger :: Integer -> a
51
52 {-# INLINE (-) #-}
53 {-# INLINE negate #-}
54 x - y = x + negate y
55 negate x = 0 - x
56
57 -- | the same as @'flip' ('-')@.
58 --
59 -- Because @-@ is treated specially in the Haskell grammar,
60 -- @(-@ /e/@)@ is not a section, but an application of prefix negation.
61 -- However, @('subtract'@ /exp/@)@ is equivalent to the disallowed section.
62 {-# INLINE subtract #-}
63 subtract :: (Num a) => a -> a -> a
64 subtract x y = y - x
65
66 instance Num Int where
67 I# x + I# y = I# (x +# y)
68 I# x - I# y = I# (x -# y)
69 negate (I# x) = I# (negateInt# x)
70 I# x * I# y = I# (x *# y)
71 abs n = if n `geInt` 0 then n else negate n
72
73 signum n | n `ltInt` 0 = negate 1
74 | n `eqInt` 0 = 0
75 | otherwise = 1
76
77 {-# INLINE fromInteger #-} -- Just to be sure!
78 fromInteger i = I# (integerToInt i)
79
80 instance Num Word where
81 (W# x#) + (W# y#) = W# (x# `plusWord#` y#)
82 (W# x#) - (W# y#) = W# (x# `minusWord#` y#)
83 (W# x#) * (W# y#) = W# (x# `timesWord#` y#)
84 negate (W# x#) = W# (int2Word# (negateInt# (word2Int# x#)))
85 abs x = x
86 signum 0 = 0
87 signum _ = 1
88 fromInteger i = W# (integerToWord i)
89
90 instance Num Integer where
91 (+) = plusInteger
92 (-) = minusInteger
93 (*) = timesInteger
94 negate = negateInteger
95 fromInteger x = x
96
97 abs = absInteger
98 signum = signumInteger