在 Haskell 中如何定义状态?

发布于 2024-12-10 01:10:41 字数 272 浏览 1 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

面犯桃花 2024-12-17 01:10:41

在 Haskell 中使用状态有两个部分。第一个只是建模和创建数据类型来表示您的事物(就像任何其他语言一样)。例如:

data Card = NumberCard Int | Jack | Queen | King | Ace
type Hand = (Card, Card)
data Player = Player Hand Int --a hand and his purse
data Action = Fold | Check | Bet Int | Raise Int
type Deck = [Card]
type TableState = ([Player], Deck)
--and functions to manipulate these, of course...

然后是如何使用这个状态的部分。你不需要知道 monad 就可以开始制作东西(而且当你掌握了基础知识时,你应该只关心高级主题)。特别是,您实际上并不需要使用“状态”,您只需要以函数式风格接收并返回这些值。

例如,回合是一个函数,它接受表状态(玩家和牌组的列表)、玩家操作列表并返回新的表状态(在给定这些操作的情况下玩完回合之后)。

playRound :: TableState -> [Action] -> TableState
playRound (players, deck) actions = ...

当然,现在您有责任确保在创建新表状态后忘记旧表状态。像 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:

data Card = NumberCard Int | Jack | Queen | King | Ace
type Hand = (Card, Card)
data Player = Player Hand Int --a hand and his purse
data Action = Fold | Check | Bet Int | Raise Int
type Deck = [Card]
type TableState = ([Player], Deck)
--and functions to manipulate these, of course...

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).

playRound :: TableState -> [Action] -> TableState
playRound (players, deck) 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文