我有以下函数用于在游戏世界的“图形”的“边缘”行走。它改变了世界的状态——特别是玩家的位置。我还需要报告一条消息,提醒玩家位置发生变化。
所以我可以返回一个 (message, newWorld) 元组,或者我可以使用 State monad。 (对吧?我对这东西很陌生。)
这是我对 monad 方法的尝试:
walk dir = do
world <- get
let attempt = filter (\e -> edgeDirection e == dir) $ edges
edges = (worldEdges world) M.! playerLoc
playerLoc = playerLocation $ worldPlayer world
case attempt of
[] -> return "You can't go that way."
(edge : _) -> do
put world'
return message
where world' = world { worldPlayer = player' }
player' = (worldPlayer world) { playerLocation = loc }
loc = edgeLocation edge
message = "You go " ++ (downcase $ show dir)
问题是,现在的功能是calls walk
有一个 State monad 需要处理。我是吗runState
它就在那里,或者我也有使用 State monad 的函数,如下所示:
parseWalk dir =
let direction = case dir of
('e' : _) -> Just East
('n' : _) -> Just North
('s' : _) -> Just South
('w' : _) -> Just West
('u' : _) -> Just Up
('d' : _) -> Just Down
_ -> Nothing
in case direction of
Just d -> walk d
Nothing -> return "You can't go that way"
那么呢parseWalk
的来电者等等?我应该尝试让这个 State monad 尽可能长时间地传递吗?我应该看到很多MonadState ...
在我的类型签名中?
这是一种思考方式:runState
需要一个初始状态作为其参数。您的代码中哪里可以使用此初始状态?这就是状态单子需要传播的距离。
注意runState
封装有状态计算,所以如果你有两个runState
并排计算时,它们不会看到彼此的状态(除非您将结果从一个传递给另一个。)这也应该给您提示“向上”多远runState
需要是。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)