使用 STM 修改和打印状态

Modify and print state using STM

我可以使用 STM 初始化状态并将其打印出来:

module Main where

import Control.Concurrent.STM

data State = State {name :: String} deriving (Show)

type MyAppState = TVar [State]

initState :: STM MyAppState
initState = newTVar [State "hi"]

main :: IO ()
main =  
  do 
    state <- atomically initState
    stateToPrint <- readTVarIO state
    putStrLn (show stateToPrint)

我已经尝试创建函数来更新状态:

updateState :: String -> State -> State 
updateState newName s = State newName : s

但我不确定如何将它放在主 'do' 块中而不让编译器抛出错误,因为它需要 State 类型,但它传递给 MyAppState.

您可以使用 writeTVar :: TVar a -> a -> STM ():

main :: IO ()
main = do 
    state <- atomically initState
    stateToPrint <- readTVarIO state
    putStrLn (show stateToPrint)
    atomically (readTVar state >>= <b>writeTVar state . fmap (updateState "foo")</b>)

我们在这里读取state的内容,然后我们通过fmap updateState传递它来更新列表中的元素,然后我们将其写入state变量

也就是说,寻找状态 monad 转换器可能会有用,例如 Control.Monad.Trans.State module of the transformers package

请注意,您的 updateState 函数未正确定义,您可能希望这样定义:

updateState :: String -> State -> State 
updateState newName (State <b>s) = State (newName ++ s)</b>