[project @ 1996-01-08 20:28:12 by partain]
[ghc-hetmet.git] / ghc / lib / hbc / Hash.hs
1 module Hash where
2 --
3 -- Hash a value.  Hashing produces an Int of
4 -- unspecified range.
5 --
6
7 class Hashable a where
8     hash :: a -> Int
9
10 instance Hashable Char where
11     hash x = ord x
12
13 instance Hashable Int where
14     hash x = x
15
16 instance Hashable Integer where
17     hash x = fromInteger x
18
19 instance Hashable Float where
20     hash x = truncate x
21
22 instance Hashable Double where
23     hash x = truncate x
24
25 instance Hashable Bin where
26     hash x = 0
27
28 #if defined(__HBC__)
29 instance Hashable File where
30     hash x = 0
31 #endif
32
33 instance Hashable () where
34     hash x = 0
35
36 instance Hashable (a -> b) where
37     hash x = 0
38
39 instance Hashable a => Hashable [a] where
40     hash l = f l 0
41         where f :: (Hashable a) => [a] -> Int -> Int
42               f [] r = r
43               f (c:cs) r = f cs (3*r + hash c)
44
45 #if defined(__OVERLAPPING_INSTANCES__)
46 instance Hashable [Char] where
47     hash l = f l 0
48         where f :: String -> Int -> Int
49               f [] r = r
50               f (c:cs) r = f cs (3*r + ord c)
51 #endif
52
53 instance (Hashable a, Hashable b) => Hashable (a,b) where
54     hash (a,b) = hash a + 3 * hash b
55
56 instance (Hashable a, Hashable b, Hashable c) => Hashable (a,b,c) where
57     hash (a,b,c) = hash a + 3 * hash b + 5 * hash c
58
59 instance (Hashable a, Hashable b, Hashable c, Hashable d) => Hashable (a,b,c,d) where
60     hash (a,b,c,d) = hash a + 3 * hash b + 5 * hash c + 7 * hash d
61
62 instance (Hashable a, Hashable b, Hashable c, Hashable d, Hashable e) => Hashable (a,b,c,d,e) where
63     hash (a,b,c,d,e) = hash a + 3 * hash b + 5 * hash c + 7 * hash d + 9 * hash e
64
65 instance Hashable Bool where
66     hash False = 0
67     hash True = 1
68
69 instance (Integral a, Hashable a) => Hashable (Ratio a) where
70     hash x = hash (denominator x) + hash (numerator x)
71
72 instance (RealFloat a, Hashable a) => Hashable (Complex a) where
73     hash (x :+ y) = hash x + hash y
74
75 #if __HASKELL1__ < 3
76 instance (Hashable a, Hashable b) => Hashable (Assoc a b) where
77     hash (x := y) = hash x + hash y
78 #endif
79
80 instance (Ix a) => Hashable (Array a b) where
81     hash x = 0 -- !!!
82
83 #if __HASKELL1__ < 3
84 instance Hashable Request where
85     hash x = 0 -- !!
86
87 instance Hashable Response where
88     hash x = 0 -- !!
89
90 instance Hashable IOError where
91     hash x = 0 -- !!
92 #endif
93
94
95 hashToMax maxhash x =
96     let h = hash x
97     in  if h < 0 then 
98             if -h < 0 then 0 
99             else (-h) `rem` maxhash
100         else h `rem` maxhash