我做了以下特定于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中)起作用。

我在黑客上发现了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替代方法或更好的使用方法?

最佳答案

我已经在几个不同的场合重写了一个俗气的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)。

[编辑:澄清的语言]

10-06 02:43