Haskell:STM writeTVar的嵌套monad错误

2sbarzqh  于 2023-10-19  发布在  其他
关注(0)|答案(1)|浏览(119)

我有以下代码

module MyLib (write) where

import Control.Monad.STM
import Control.Concurrent.STM.TVar

write :: STM (TVar Störm) -> Störm -> IO ()
write state' new = atomically $ write' state'
      where
        write' :: STM (TVar Störm) -> STM ()
        write' state' = write'' <$> state'
        write'' :: TVar Störm -> STM ()
        write'' state' = writeTVar state' new

使用依赖关系STM
我收到以下错误

src/MyLib.hs:39:25: error:
    • Couldn't match type ‘STM ()’ with ‘()’
      Expected: TVar Störm -> ()
        Actual: TVar Störm -> STM ()
    • In the first argument of ‘(<$>)’, namely ‘write''’
      In the expression: write'' <$> state'
      In an equation for ‘write'’: write' state' = write'' <$> state'
   |
39 |         write' state' = write'' <$> state'

在我的测试中,它将Monad嵌套到STM (STM ())。却不知道如何解决

oxosxuxt

oxosxuxt1#

问题出在write'' <$> state'项上。在这种情况下,(<$>)具有类型:

(<$>) :: (TVar Störm -> STM ()) -> STM (TVar Störm) -> STM (STM ())

write'' <$> state' :: STM (STM ())

但预期类型为STM ()
要解决这个问题,您可以执行以下操作:

join $ write'' <$> state'

但更简单的是:

write'' =<< state'

或:

state' >>= write''

但是,我会这样写:

write :: STM (TVar Störm) -> Störm -> IO ()
write action new = atomically $ do
    var <- action
    writeTVar var new

相关问题