6

我做了以下特定于 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 是否有替代方法或比我更好的使用方法?

4

1 回答 1

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
    ...

然后很容易抽象出你的记忆例程(尽管你可能想IORef在这种情况下用MVar. 替换)

[编辑:澄清的措辞]

于 2009-07-07T15:51:46.370 回答