Haskell中的软件事务存储器:无法将预期的STM a0类型与实际的IO类型进行匹配()

tim*_*lim 2 haskell stm

我有一个定义帐户的小程序,一个提现功能并尝试从中提现。但是,它不会编译到期,并引发以下错误:

Couldn't match expected type ‘(STM a0 -> IO a0)
                                    -> STM () -> IO ()’
                  with actual type ‘IO ()’
Run Code Online (Sandbox Code Playgroud)

似乎编译器无法识别从STM到IO的转换。任何指针都很棒。

import System.IO
import Control.Concurrent.STM

type Account = TVar Int

withdraw :: Account -> Int -> STM ()
withdraw acc amount = do
    bal <- readTVar acc    
    writeTVar acc (bal - amount)

good :: Account -> IO ()
good acc = do
    hPutStr stdout "Withdrawing..."
    {-hi-}atomically{-/hi-} (withdraw acc 10)

main = do
    acc <- atomically (newTVar 200)
    good acc 
    hPutStr stdout "\nDone!\n"
Run Code Online (Sandbox Code Playgroud)

Wil*_*sem 6

{-hi-}{-/hi-}注释结果“缩进”了automically,这样的结果,你写hPutStr stdout "Withdrawing..." atomically (withdraw acc 10)。例如,如果您编写:

good :: Account -> IO ()
good acc = do
        hPutStr stdout "Withdrawing..."
 {-hi-} atomically (withdraw acc 10)
Run Code Online (Sandbox Code Playgroud)

它工作正常,因为“噪声”({-hi-}注释)不会导致内联atomically函数。

注释在语义上确实没有任何作用,但是您可以考虑将其替换为空格。