Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to merge two hashtables? #84

Open
N0lim opened this issue Aug 8, 2023 · 2 comments
Open

How to merge two hashtables? #84

N0lim opened this issue Aug 8, 2023 · 2 comments

Comments

@N0lim
Copy link

N0lim commented Aug 8, 2023

No description provided.

@erikd
Copy link
Collaborator

erikd commented Aug 8, 2023

A naive solution would be to convert the two Hashtables to lists, concatenate the two lists and then convert the resulting list back to a Hashtable.

Warning, this code has never been compiled.

naiveMerge :: HashTable k v -> HashTable k v -> ST (HashTable k v)
naiveMerge a b = do
     as <-toList a
     bs <- toList b
     fromList $ as + bs

And no thought whatever has gone into how to handle key/value pairs that exist in both lists.

@N0lim
Copy link
Author

N0lim commented Aug 9, 2023

I wrote this mutable version and a test for it, I'm sure a more flexible version can be made using mutate or maybe an immutable version will turn out

import Data.HashTable.Class
import qualified Data.HashTable.ST.Cuckoo as C
import Control.Monad.ST

--merge :: (HashTable h1, HashTable h2, Hashable a) => h1 s a b -> h2 s a b -> ST s ()
merge tbl1 tbl2 = do
  l1 <- toList tbl1
  mapM (uncurry (insert tbl2)) l1 
  return ()

testST = do
  tbl1 <- C.new
  insert tbl1 "a" True
  insert tbl1 "b" True
  tbl2 <- C.new
  insert tbl2 "b" False
  insert tbl2 "c" False
  merge tbl1 tbl2
  a <- Data.HashTable.Class.lookup tbl2 "a"
  b <- Data.HashTable.Class.lookup tbl2 "b"
  c <- Data.HashTable.Class.lookup tbl2 "c"
  return (a, b, c)

test = runST testST

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants