How do you define state in Haskell?

How do you define state in Haskell? My first idea was to use algebraic data types. I also heard about the state monad, but I do not know what it is. An example is Texas Hold'em poker. We must present the following states:

  • Two cards that you hold in your hands.
  • Cards on the board
  • The actions of the players in front of you, which may be:
    • collapse
    • check
    • rate x
    • raise x
  • Pot size
  • Amount for call
  • Amount of money (limited poker)
+4
source share
1 answer

Haskell has two parts for using state. The first is just modeling and creating Datatypes to represent your things (as in any other language). For instance:

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 part of how you use this condition. You do not need to know the monads to start doing things (and you only need to worry about advanced topics when you have the basics, mastered in any case). In particular, you do not need to use the β€œstate”, you just need to get and return these values ​​in a functional style.

For example, a round will be a function that takes the state of the table (list of players and the deck), a list of player actions and returns the new state of the table (after the ore has been played taking into account these actions).

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

Of course, now your responsibility is to make sure that the old state of the table is forgotten after creating a new one. Things like the state monad help with such an organizational problem.

+10
source

All Articles