gpt4 book ai didi

Haskell:通用 IORef、MVar?

转载 作者:行者123 更新时间:2023-12-02 20:41:25 32 4
gpt4 key购买 nike

我制作了以下特定于 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 的替代方案或比我更好的使用方法?

最佳答案

我在几个不同的场合重写了一个俗气的小 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
...

然后很容易抽象出您的内存例程(尽管您可能想用 MVar 替换此上下文中的 IORef。)

[编辑:澄清用语]

关于Haskell:通用 IORef、MVar?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1091629/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com