在 Haskell 中如何定义状态?
在 Haskell 中如何定义状态?我的第一个想法是使用代数数据类型。我也听说过状态单子,但我不太知道它是什么。 作为一个例子,让我们使用德州扑克。我们必须表示以下状态:
- 你手里拿着的两张牌
- 棋盘上的牌
- 你面前的玩家的动作,可以是:
- 折叠
- 检查
- 下注x
- 提高 x
- 底池大小
- 跟注金额
- 加注金额(有限扑克)
How do you define state in Haskell? My first idea was to use algebraic data types. I've also heard about the state monad, but I don't really know what it is.
As an example, lets use Texas hold'em poker. We have to represent the following states:
- The two cards you hold in your hands
- The cards on the board
- The actions of the players before you, which can be:
- fold
- check
- bet x
- raise x
- The size of the pot
- The amount of money to call
- The amount of money to raise (limited poker)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 Haskell 中使用状态有两个部分。第一个只是建模和创建数据类型来表示您的事物(就像任何其他语言一样)。例如:
然后是如何使用这个状态的部分。你不需要知道 monad 就可以开始制作东西(而且当你掌握了基础知识时,你应该只关心高级主题)。特别是,您实际上并不需要使用“状态”,您只需要以函数式风格接收并返回这些值。
例如,回合是一个函数,它接受表状态(玩家和牌组的列表)、玩家操作列表并返回新的表状态(在给定这些操作的情况下玩完回合之后)。
当然,现在您有责任确保在创建新表状态后忘记旧表状态。像 State monad 这样的东西有助于解决这种组织问题。
There are two parts to using state in Haskell. The first one is just modeling and creating Datatypes to represent your things (just like in any other language). For example:
Then there is the part of how you use this state. You don't need to know monads to start making stuff (and you should only bother with the advanced topics when you have the basics mastered anyway). In particular you don't really need to use "state", you just need to receive and return these values in functional style.
For example, a round would be a function that takes a table state (list of players and the deck), a list of player actions and returns a new table state (after the roud had been played given these actions).
Of course it is now your responsibility to make sure that the old table state is forgotten after you create a new one. Things like the State monad help with this kind of organizational issue.