Haskell如何修改RWST环境变量?

How to modify RWST environment variables in Haskell?

我正在尝试在名为“GLFW-b-Demo”的现有项目上构建我自己的项目。

它显然是在使用一种叫做“RWST”的东西来模拟环境和状态:

data Env = Env
    { envEventsChan    :: TQueue Event
    , envWindow        :: !GLFW.Window
    , envGear1         :: !GL.DisplayList
    , envGear2         :: !GL.DisplayList
    , envGear3         :: !GL.DisplayList
    , envPlane         :: !GL.DisplayList
    , envBlobs         :: ![Blob]
    , envZDistClosest  :: !Double
    , envZDistFarthest :: !Double
    }

data State = State
    { stateWindowWidth     :: !Int
    , stateWindowHeight    :: !Int
    , stateXAngle          :: !Double
    , stateYAngle          :: !Double
    , stateZAngle          :: !Double
    , stateGearZAngle      :: !Double
    , stateZDist           :: !Double
    , stateMouseDown       :: !Bool
    , stateDragging        :: !Bool
    , stateDragStartX      :: !Double
    , stateDragStartY      :: !Double
    , stateDragStartXAngle :: !Double
    , stateDragStartYAngle :: !Double
    }

type Demo = RWST Env () State IO

从那个环境中检索一些东西很容易:

blobs <- asks envBlobs

但我还需要能够修改那些“变量”的值。 我是否需要将其移动到状态才能更改它的值,或者我是否也可以修改“env”部分的内容?

But I also need to be able to modify the value of those "variables". Would I need to move that to the state, to be able to change it's value or can I also modify the contents of the "env" part of things?

这取决于您是想在您控制的计算中“本地”修改这些 env 值,还是想为之后可能出现的任何可能计算修改它们。

在第一种情况下,您可以使用 local:

local :: (r -> r) -> RWST r w s m a -> RWST r w s m a

当我们传递给 localRWST 计算退出时,环境 r 中的值将 return 为其原始版本,未被 r -> r函数。

但是,如果您希望更改具有“粘性”,则需要将这些值移动到状态并使用像 put or modify.

这样的函数

一个例子:

import Control.Monad.IO.Class
import Control.Monad.Trans.RWS.Strict

action :: RWST Int () Char IO ()
action = do
  local succ $ do -- affects only the nested action
    v <- ask 
    liftIO $ print v
  do
    v <- ask 
    liftIO $ print v -- isn't affected by local
  modify succ -- change seen by the following actions
  do
    s <- get 
    liftIO $ print s -- is affected by modify

main :: IO ()
main = do
  (_, _, _) <- runRWST action 0 'a'
  return ()
-- Results:
-- 1
-- 0
-- 'b'