[project @ 1999-09-16 19:54:37 by sof]
[ghc-hetmet.git] / ghc / tests / programs / jeff-bug / Words.hs
1 module Words where
2
3 import Word
4 import Int
5 import Ix
6
7 -- Begin Signature ---------------------------------------------------------
8
9 {- 
10 The Word class captures both the common operations and class instances
11 that you would want from words of different sizes.  
12 -}
13
14 class (Ix w,Num w,Integral w,Bounded w, Eq w) => Word w where
15   --intToWord       :: Int -> w
16   num_half        :: w
17   num_bytes       :: w
18   max_signed      :: w
19   min_signed      :: w
20   max_signed_half :: w
21   sign            :: w -> w
22   unsign          :: w -> w
23   --toWord          :: Integral a => a -> w
24   sign_half       :: w -> w
25
26   --toWord      = intToWord . toInt
27   sign_half n = n `signedModulus` num_half
28
29 class Word w => Word2 i w where
30   toWord :: i -> w
31
32 {-instance Word Int-}
33 {-instance Word Word8-}
34 {-instance Word Word32-}
35
36 -- This isn't set yet because Word64 is not set to Num in Hugs
37 -- instance Word Word64 
38
39 -- End Signature ---------------------------------------------------------
40
41
42
43
44 instance Word Int where
45   num_half        = mk_num_half 31
46   num_bytes       = mk_num_bytes 31
47   max_signed      = mk_max_signed 31
48   min_signed      = mk_min_signed 31
49   max_signed_half = mk_max_signed_half 31
50   sign            = mk_sign 31
51   unsign          = mk_unsign 31
52
53 instance Integral i => Word2 i Int where
54   toWord          = toInt
55
56 instance Word Word8 where
57   num_half        = mk_num_half 8 
58   num_bytes       = mk_num_bytes 8      
59   max_signed      = mk_max_signed 8
60   min_signed      = mk_min_signed 8
61   max_signed_half = mk_max_signed_half 8
62   sign            = mk_sign 8
63   unsign          = mk_unsign 8
64
65 instance Integral i => Word2 i Word8 where
66   toWord          = intToWord8 . toInt
67
68
69 instance Word Word32 where
70   num_half        = mk_num_half 32
71   num_bytes       = mk_num_bytes 32      
72   max_signed      = mk_max_signed 32
73   min_signed      = mk_min_signed 32
74   max_signed_half = mk_max_signed_half 32
75   sign            = mk_sign 32
76   unsign          = mk_unsign 32
77
78 instance Integral i => Word2 i Word32 where
79   toWord          = intToWord32 . toInt
80
81 mk_num_half  x       = 2^(x `div` 2)
82 mk_num_bytes x       = 2^(x `div` 4)
83 mk_max_signed x      = 2^(x-1) - 1
84 mk_min_signed x      = -2^(x-1)
85 mk_max_signed_half x = 2^((x `div` 2) - 1) - 1
86 mk_sign x n          = fromInteger $ n' `signedModulus` ((2^x)::Integer)
87    where n' = toInteger n
88 mk_unsign x n        = fromInteger $ if n' >=0 then n' else n' + 2^x'
89    where n' = toInteger n
90          x' = toInteger x 
91
92 signedModulus x m
93   = if modNum <= (m `div` 2) - 1
94       then modNum
95       else m - modNum
96     where
97       modNum = x `mod` m
98
99