开发者

How do you define state in Haskell?

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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜