1
{-| Provides 'hash' function for many data types
3
module Hash(Hash, combineHash, emptyHash, hashToInt, hashToMax, Hashable(..)) where
12
newtype Hash = H Int deriving (Eq)
14
----instance Show Hash where
16
combineHash :: Hash -> Hash -> Hash
17
combineHash (H x) (H y) = H (x+y)
22
class Hashable a where
25
instance Hashable Char where
26
hash x = H $ fromEnum x
28
instance Hashable Int where
31
instance Hashable Integer where
32
hash x = H $ fromInteger x
34
instance Hashable Float where
35
hash x = H $ truncate x
37
instance Hashable Double where
38
hash x = H $ truncate x
40
instance Hashable (IO a) where
43
instance Hashable () where
46
instance Hashable (a -> b) where
49
instance (Hashable a) => Hashable (Maybe a) where
51
hash (Just x) = hash x
53
instance (Hashable a, Hashable b) => Hashable (Either a b) where
54
hash (Left x) = hash x
55
hash (Right y) = hash y
58
--instance Hashable a => Hashable [a] where
61
instance (Hashable a,Enum a) => Hashable [a] where
63
where f :: Enum b => [b] -> Int -> Int
65
f (c:cs) r = f cs (3*r + fromEnum c)
68
instance (Hashable a, Hashable b) => Hashable (a,b) where
69
hash (a,b) = H $ (case hash ( a ) of H h -> h) + 3 * (case hash ( b ) of H h -> h)
71
instance (Hashable a, Hashable b, Hashable c) => Hashable (a,b,c) where
72
hash (a,b,c) = H $ (case hash ( a ) of H h -> h) + 3 * (case hash ( b ) of H h -> h) + 5 * (case hash ( c ) of H h -> h)
74
instance (Hashable a, Hashable b, Hashable c, Hashable d) => Hashable (a,b,c,d) where
75
hash (a,b,c,d) = H $ (case hash ( a ) of H h -> h) + 3 * (case hash ( b ) of H h -> h) + 5 * (case hash ( c ) of H h -> h) + 7 * (case hash ( d ) of H h -> h)
77
instance (Hashable a, Hashable b, Hashable c, Hashable d, Hashable e) => Hashable (a,b,c,d,e) where
78
hash (a,b,c,d,e) = H $ (case hash ( a ) of H h -> h) + 3 * (case hash ( b ) of H h -> h) + 5 * (case hash ( c ) of H h -> h) + 7 * (case hash ( d ) of H h -> h) + 9 * (case hash ( e ) of H h -> h)
80
instance Hashable Bool where
84
instance (Integral a, Hashable a) => Hashable (Ratio a) where
85
hash x = H $ (case hash ( denominator x ) of H h -> h) + (case hash ( numerator x ) of H h -> h)
87
instance (RealFloat a, Hashable a) => Hashable (Complex a) where
88
hash (x :+ y) = H $ (case hash ( x ) of H h -> h) + (case hash ( y ) of H h -> h)
90
instance (Ix a) => Hashable (Array a b) where
93
hashToInt :: Int -> Hash -> Int
99
else (-h) `rem` maxhash
102
hashToMax maxhash x =
107
else (-h) `rem` maxhash