0

I have a map where multiple keys can map to the same value. I'd like to do reverse lookups, such that given a value, I get a list of all keys that map to this value. Note that unlike Data.Bimap my map is not 1:1 but n :1.

Also, the reverse lookup should not take O(n) like running through all map entries would require but rather O(log n) or better like with a reverse index. The map will contain many ten-thousands of entries with a high load of add/remove/lookup operations.

Is such a data structure available in functional form (Haskell or Frege preferred)?

Cactus
  • 27,075
  • 9
  • 69
  • 149
Dierk
  • 1,308
  • 7
  • 13
  • 5
    The linked code is just a wrapper around two maps. Why not make a wrapper around a map and a multimap? – n. m. could be an AI Dec 28 '15 at 16:35
  • And if you really only have O(100,000) entries and need speed on add/remove/lookup, you should probably use `data N1Bimap a b = N1Bimap !(HashMap a b) !(HashMap b (HashSet a))` for some added speed, if your fundamental types are `Hashable`. (You can automatically derive `Hashable` in GHC, too.) – CR Drost Dec 28 '15 at 17:30
  • Thanks for the comment. I'm afraid this is not as efficient as I hoped for since every add/remove in the first map will not only cause a change in the reverse map but a rundown through its value list in O(m) where m is the size of the reverse lookup result size. – Dierk Dec 28 '15 at 19:31
  • 2
    @Dierk: That is why you then use a set/hashset data structure for the reverse map, to get O(log n + log m) removals. – CR Drost Dec 28 '15 at 19:41
  • Ok, yes, overlooked the HashSet. Thanks! – Dierk Dec 28 '15 at 19:43
  • Even if you cannot hash, you can use Map b (Set a) instead of multimap for faster deletions. – n. m. could be an AI Dec 29 '15 at 09:45

0 Answers0