[project @ 1996-01-18 16:33:17 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 {-# SPECIALISE instance Hashable [Char] #-}
46
47 instance (Hashable a, Hashable b) => Hashable (a,b) where
48     hash (a,b) = hash a + 3 * hash b
49
50 instance (Hashable a, Hashable b, Hashable c) => Hashable (a,b,c) where
51     hash (a,b,c) = hash a + 3 * hash b + 5 * hash c
52
53 instance (Hashable a, Hashable b, Hashable c, Hashable d) => Hashable (a,b,c,d) where
54     hash (a,b,c,d) = hash a + 3 * hash b + 5 * hash c + 7 * hash d
55
56 instance (Hashable a, Hashable b, Hashable c, Hashable d, Hashable e) => Hashable (a,b,c,d,e) where
57     hash (a,b,c,d,e) = hash a + 3 * hash b + 5 * hash c + 7 * hash d + 9 * hash e
58
59 instance Hashable Bool where
60     hash False = 0
61     hash True = 1
62
63 instance (Integral a, Hashable a) => Hashable (Ratio a) where
64     hash x = hash (denominator x) + hash (numerator x)
65
66 instance (RealFloat a, Hashable a) => Hashable (Complex a) where
67     hash (x :+ y) = hash x + hash y
68
69 #if __HASKELL1__ < 3
70 instance (Hashable a, Hashable b) => Hashable (Assoc a b) where
71     hash (x := y) = hash x + hash y
72 #endif
73
74 instance (Ix a) => Hashable (Array a b) where
75     hash x = 0 -- !!!
76
77 #if __HASKELL1__ < 3
78 instance Hashable Request where
79     hash x = 0 -- !!
80
81 instance Hashable Response where
82     hash x = 0 -- !!
83
84 instance Hashable IOError where
85     hash x = 0 -- !!
86 #endif
87
88
89 hashToMax maxhash x =
90     let h = hash x
91     in  if h < 0 then 
92             if -h < 0 then 0 
93             else (-h) `rem` maxhash
94         else h `rem` maxhash