Skip to content

Instantly share code, notes, and snippets.

@isovector
Last active November 29, 2015 03:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isovector/860db25dc1f1b16fc697 to your computer and use it in GitHub Desktop.
Save isovector/860db25dc1f1b16fc697 to your computer and use it in GitHub Desktop.
module Test where
import Control.Concurrent.MVar
import Control.Monad.IO.Class
import Control.Monad (join)
-- Memoize an IO result
memoIO :: MonadIO m => m a -> m (m a)
memoIO action = do
ref <- liftIO $ newMVar Nothing
return $ do
x <- maybe action return =<< liftIO (takeMVar ref)
liftIO . putMVar ref $ Just x
return x
--------------
-- prints "hi" twice, returns 5
main :: IO Int
main = do
hi5
hi5
where hi5 = join . memoIO $ do
putStrLn "hi"
return 5
--------------
-- prints "hi" once, returns 4
main2 :: IO Int
main2 = do
hi <- hi4
hi
hi
where hi4 = memoIO $ do
putStrLn "hi"
return 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment