初始化后返回TVar

时间:2012-12-31 02:59:57

标签: haskell concurrency

是否可以在do块中返回新创建的TVar?我尝试使用以下代码实现此目的:

type Buffer a = TVar [[(a,a)]]

newBuffer :: STM (Buffer a)
newBuffer = newTVar [[]]

launchGhosts :: [[(String,String)]] -> Buffer String
launchGhosts unblocked = do buff <- atomically newBuffer
                            atomically $ put buff unblocked
                            return buff


computeBlock :: Buffer String -> IO()
computeBlock buff = do i <- atomically $ get buff
                       putStrLn $ show i

put :: Buffer a -> [[(a,a)]] -> STM ()
put buff x = do writeTVar buff x

get :: Buffer a -> STM [[(a,a)]]
get buff = do x <- readTVar buff
              return x

这应该允许我初始化共享内存并在程序中的其他位置使用它。我想分离内存初始化的主要原因是多次调用并发函数,而不是一次又一次初始化内存。

类型检查程序会产生这两个错误:

pacman.hs:65:29:
No instance for (Monad TVar)
  arising from a do statement
Possible fix: add an instance declaration for (Monad TVar)
In a stmt of a 'do' block: buff <- atomically newBuffer
In the expression:
  do { buff <- atomically newBuffer;
       atomically $ put buff unblocked;
       computeBlock buff;
       return buff }
In an equation for `launchGhosts':
    launchGhosts unblocked
      = do { buff <- atomically newBuffer;
             atomically $ put buff unblocked;
             computeBlock buff;
             .... }

pacman.hs:65:37:
    Couldn't match expected type `TVar t0' with actual type `IO a0'
    In the return type of a call of `atomically'
    In a stmt of a 'do' block: buff <- atomically newBuffer
    In the expression:
      do { buff <- atomically newBuffer;
           atomically $ put buff unblocked;
           computeBlock buff;
           return buff }

有人知道问题是什么,或者可能是实现此代码背后的另一种方法吗?

更新:

launchGhosts :: [[(String,String)]] -> IO(Buffer String)
launchGhosts unblocked = do buff <- atomically newBuffer
                            atomically $ put buff unblocked
                            return buff


computeBlock :: IO(Buffer String) -> IO()
computeBlock buff = do i <- atomically $ get buff
                       putStrLn $ show i

更新

pacman.hs:71:46:
Couldn't match expected type `Buffer a0'
            with actual type `IO (Buffer String)'
In the first argument of `get', namely `buff'
In the second argument of `($)', namely `get buff'
In a stmt of a 'do' block: i <- atomically $ get buff

1 个答案:

答案 0 :(得分:1)

解决方案是将launchGhosts声明为

launchGhosts :: [[(String,String)]] -> IO (Buffer String)

问题在于您宣布launchGhostsBuffer String,即TVar [[(String, String)]]。由于launchGhosts使用do块,因此需要Monad个实例作为其结果类型,根据您的签名TVar。这就是第一个错误。

另一个问题是atomically的类型为STM a -> IO a,因此atomically newBufferIO something(实际类型)。但是你在do块中使用它,它被声明为Buffer(即TVar)类型,因此它也应该具有该类型(预期类型)。这就是第二个错误。

编辑:

为什么要更改computeBlock的类型签名?我从来没有说过computeBlock