Skip to content

Instantly share code, notes, and snippets.

@thelissimus
Created February 10, 2025 23:20
Show Gist options
  • Select an option

  • Save thelissimus/c658a47937c2c665d2a3f2595308bed1 to your computer and use it in GitHub Desktop.

Select an option

Save thelissimus/c658a47937c2c665d2a3f2595308bed1 to your computer and use it in GitHub Desktop.
brokkr-hashtables missing pieces
module Utils (module Utils) where
import Brokkr.HashTable qualified as HT
import Control.Monad
import Control.Monad.Primitive
import Data.Hashable (hashWithSalt)
instance HT.Hash ShortText where
hash txt = HT.HashFn (\st -> hashWithSalt st txt)
alterM :: (PrimMonad m, Eq k, HT.Hash k) => HashTable (PrimState m) k v -> (Maybe v -> m (Maybe v)) -> k -> m ()
alterM ht f k =
HT.lookup
ht
k
(\v -> f (Just v) >>= \case Nothing -> void (HT.delete ht k); Just v' -> HT.insert ht k v')
(f Nothing >>= \case Nothing -> pure (); Just v' -> HT.insert ht k v')
{-# INLINE alterM #-}
-- for this benchmark we don't need the ability to be able to delete and usage of this leads to a bit better results (1-2%)
-- to be honest, I am in the realm of microoptimizations at this point :)
alterM' :: (PrimMonad m, Eq k, HT.Hash k) => HashTable (PrimState m) k v -> (Maybe v -> m v) -> k -> m ()
alterM' ht f k = HT.lookup ht k (\v -> f (Just v) >>= HT.insert ht k) (f Nothing >>= HT.insert ht k)
{-# INLINE alterM' #-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment