我正在与Haskell一起创建一个简单的终端游戏,并且在执行卫生系统时遇到了很大的困难。最后将更改后的健康点保存到文本文件中,这样就可以将其保持为“变量”。
我的代码:
readHealth = do
theFile <- openFile "health.txt" ReadMode
healthPoints <- hGetContents theFile
return healthPoints 这里的问题是我不能访问"healthPoints“在readHealth之外的东西.有什么建议吗?
发布于 2020-05-11 20:03:00
这不是解决问题的适当办法。从IO monad中提取数据是不可能的,因为这不是它的目的。相反,您应该考虑使用State monad家族(或者是近亲StateT),它允许您通过程序携带可变值,如下所示:
data Game = Game { health :: Int, ... }
type GameState = State Game然后,要从主线程读取您的值,可以使用:
gameloop :: GameState ()
gameloop = do
currentHealth <- gets health
pure ()要更新健康状况,您需要一个简短的功能:
updateHealth :: Int -> Game -> Game
updateHealth newHealth game = game { health = newHealth }然后,您可以通过以下方式将健康设置为10:
gameloop :: GameState ()
gameloop = do
modify $ updateHealth 10
pure ()用法示例:
> evalState (gets health) (Game { health = 10 })
10
> evalState (modify (updateHealth 20) >> gets health) (Game { health = 10 })
20*实际上可以使用IO从unsafePerformIO中提取值,但是顾名思义,这样做是不安全的,除非您真正知道自己在做什么。
https://stackoverflow.com/questions/61737912
复制相似问题