Skip to content

Commit 89d753f

Browse files
committed
Nicer Hashable instance implementation
1 parent 2b08194 commit 89d753f

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

Data/HashMap/Base.hs

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -220,15 +220,20 @@ equal t1 t2 = go (toList' t1 []) (toList' t2 [])
220220
go _ _ = False
221221

222222
instance (Hashable k, Ord k, Hashable v) => Hashable (HashMap k v) where
223-
hashWithSalt salt = L.foldl' (\h (L k v) -> h `H.hashWithSalt` k `H.hashWithSalt` v) salt . toList''
223+
hashWithSalt salt hm = go salt (toList' hm [])
224224
where
225-
-- Order 'Leaf' s with (hash, k) ordering
226-
toList'' :: HashMap k v -> [Leaf k v]
227-
toList'' hm = concatMap f (toList' hm [])
228-
f :: HashMap k v -> [Leaf k v]
229-
f (Leaf _ l) = [l]
230-
f (Collision _ a) = L.sortBy (comparing leafKey) (A.toList a)
231-
f _ = []
225+
go :: Int -> [HashMap k v] -> Int
226+
go salt [] = salt
227+
go salt (Leaf _ l : tl) = salt `hashLeafWithSalt` l `go` tl
228+
go salt (Collision _ a : tl) = salt `hashCollisionWithSalt` a `go` tl
229+
go salt (_ : tl) = salt `go` tl
230+
231+
hashLeafWithSalt :: Int -> Leaf k v -> Int
232+
hashLeafWithSalt s (L k v) = s `H.hashWithSalt` k `H.hashWithSalt` v
233+
234+
hashCollisionWithSalt :: Int -> A.Array (Leaf k v) -> Int
235+
hashCollisionWithSalt s a = L.foldl' (hashLeafWithSalt) s (L.sortBy (comparing leafKey) (A.toList a))
236+
232237
leafKey :: Leaf k v -> k
233238
leafKey (L k _) = k
234239

0 commit comments

Comments
 (0)