在 State Monad 中获取 Gamestate 值

Getting Gamestate value in State Monad

我正在学习状态单子,但我有点困惑。

我有一个数据类型

data GameState = GameState (Map String Double) Double Bool
deriving (Eq, Show)

第二个参数Double是一个方向

当然还有状态 monad 定义

newtype State s a = StateOf (s -> (s, a))
deState (StateOf stf) = stf
get = StateOf (\s0 -> (s0, s0))
put s = StateOf (\s0 -> (s , ()))
modify f = get >>= \s -> put (f s)

那么如何写一个函数来获取方向

getDirection:: State GameState Double

我试过了

getDirection = do
     x <- get
     return x

但这只是 return GameState,我如何获得当前的方向?

当我想改变方向时,我使用 put 还是 modify?

让我们从你目前拥有的开始:

getDirection :: State GameState Double
getDirection = do
     x <- get
     return x

(顺便说一句,这实际上与 getDirection = get 相同,因为您只是 运行 get 和 returning 它的 return 值。)

首先,这里的x是什么类型?你的状态是 GameState 类型,get 只是获取状态,所以 x :: GameState。所以我们可以对其进行模式匹配得到:

getDirection :: State GameState Double
getDirection = do
     (GameState map dir bool) <- get
     return (GameState map dir bool)

在这一点上应该很明显该怎么做:简单地 return dir 而不是 (GameState map dir bool).

And when I want to change the direction do I use put or modify?

你真的不应该在同一个问题中问两个问题 post,但要回答这个问题,让我们看看它们的类型:

put    :: s        -> State s ()
modify :: (s -> s) -> State s ()

想法是 put 只是写一个新状态,而 modify 获取现有状态并使用给定函数修改它。这些函数实际上是等价的,这意味着您可以用另一个替换其中一个函数:

-- write ‘put’ using ‘modify’
put s = modify (\_oldState -> s)

-- write ‘modify’ using ‘put’ (and ‘get’)
modify f = do
    oldState <- get
    put $ f oldState

然而,通常在不同的情况下使用 putmodify 更容易。例如,如果您想在不引用旧状态的情况下编写一个全新的状态,请使用 put;如果你想获取现有状态并稍微更改它,请使用 modify。在你的情况下,你只想改变方向,所以使用 modify 最简单,这样你就可以参考以前的状态改变状态:

changeDirTo :: Double -> State GameState ()
changeDirTo newDir = modify (\(GameState map _ bool) -> GameState map newDir bool)

-- you can also do it using ‘put’, but it’s a bit harder and less elegant:
changeDirTo2 :: Direction -> State GameState ()
changeDirTo2 newDir = do
    (GameState map _ bool) <- get
    put $ GameState map newDir bool

另一方面,如果您(比如说)想要分配一个全新的 GameStateput 会更容易:

putNewGameState :: GameState -> State GameState ()
putNewGameState gs = put gs

-- the above is the same as:
-- putNewGameState = put

-- you can also do it using ‘modify’, but it’s a bit harder and less elegant:
putNewGameState2 :: GameState -> State GameState ()
putNewGameState2 gs = put (\_oldState -> gs)