我做了以下函数,该函数特定于IO monad:
memoIO :: MonadIO m => m a -> IO (m a)
memoIO action = do
ref <- newMVar Nothing
return $ do
x <- maybe action return =<< liftIO (takeMVar ref)
liftIO . putMVar ref $ Just x
return x
使用示例:
main :: IO ()
main = do
p <- memoIO $ putStrLn "hello"
p
p
打印一次“hello
”。
我希望(一个小小的烦恼)让它尽可能多地工作(不仅仅是在IO中)。
我发现了关于hackage的stateref,我的代码看起来像这样:
{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, Rank2Types, UndecidableInstances #-}
import Data.MRef
class (NewMRef r m a, DefaultMRef r m a, PutMRef r m a, TakeMRef r m a) => MRef r m a
instance (NewMRef r m a, DefaultMRef r m a, PutMRef r m a, TakeMRef r m a) => MRef r m a
memo :: (MRef r m (Maybe a), Monad s) => (forall x. m x -> s x) -> s a -> m (s a)
memo liftFunc action = do
ref <- newDefaultMRef Nothing
return $ do
x <- maybe action return =<< liftFunc (takeDefaultMRef ref)
liftFunc . putDefaultMRef ref $ Just x
return x
有没有替代stateref或更好的方式来使用它?
答案 0 :(得分:7)
我在几个不同的场合重写了一个俗气的小MonadRef
课程供我个人使用,有人可能在Hackage上有一个,但我找不到一个没有其他行李的人。
class Monad m => MonadRef m where
type Ref m :: * -> *
newRef :: a -> Ref m a
writeRef :: Ref m a -> -> m ()
readRef :: Ref m a -> m a
instance MonadRef IO where
type Ref IO = IORef
newRef = newIORef
writeRef = writeIORef
readRef = writeIORef
instance MonadRef STM where
type Ref STM = TVar
...
instance MonadRef (ST s) where
type Ref (ST s) = STRef s
...
然后很容易抽象出你的memoization例程(尽管你可能希望在这个上下文中用IORef
替换MVar
。)
[编辑:澄清的废物]