gpt4 book ai didi

haskell - 在 State Monad 中获取 Gamestate 值

转载 作者:行者123 更新时间:2023-12-02 19:55:29 24 4
gpt4 key购买 nike

我正在学习状态单子(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

但是这只会返回 GameState,我如何获取当前的方向?

当我想改变方向时,我应该使用 put 还是修改?

最佳答案

让我们从目前为止所拥有的内容开始:

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

(顺便说一句,这实际上与 getDirection = get 相同,因为您只是运行 get 并返回其返回值。)

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

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

此时应该做什么是显而易见的:只需返回 dir 而不是 (GameState map dir bool)

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

你不应该在同一篇文章中问两个问题,但为了回答这个问题,让我们看看它们的类型:

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)

关于haskell - 在 State Monad 中获取 Gamestate 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57194376/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com