Skip to content

Instantly share code, notes, and snippets.

@kuribas
Created August 11, 2021 08:26
Show Gist options
  • Save kuribas/6d63a4b9be2ac210162b4c9ee2ab10ca to your computer and use it in GitHub Desktop.
Save kuribas/6d63a4b9be2ac210162b4c9ee2ab10ca to your computer and use it in GitHub Desktop.
memoize
memoize2 :: (Eq a, Hashable a) => (a -> IO b) -> IO (a -> b)
memoize2 f = do
ref <- newIORef HashMap.empty
pure $ \x ->
do mp <- readIORef ref
case HashMap.lookup x mp of
Nothing -> unsafePerformIO $ do
res <- f x
writeIORef ref $ HashMap.insert x res mp
pure res
Just res -> pure res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment