5

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)
D. Nusbaum
  • 65
  • 8
Luke
  • 5,771
  • 12
  • 55
  • 77
  • possible duplicate of [Haskell and State](http://stackoverflow.com/questions/3944170/haskell-and-state) – John L Oct 14 '11 at 15:52

1 Answers1

10

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.

hugomg
  • 68,213
  • 24
  • 160
  • 246
  • 3
    "you should only bother with the advanced topics when you have the basics mastered anyway" -- meh, to each his own. Forcing myself into the basics before allowing myself to think about the stuff that excites me is the surest way to kill my inspiration. – luqui Oct 14 '11 at 17:12
  • I'm with @luqui on this one. You gotta run before you can walk. – rampion Oct 14 '11 at 17:47
  • 1
    I am not that sure. I can only really grok an abstraction after I know what it is replacing and why replacing that is a good idea in the first place. – hugomg Oct 14 '11 at 18:43
  • @missingno: Agreed. But I don't always need to grok in full before I can use something. – rampion Oct 14 '11 at 19:46
  • why not `Integer`? – Sapphire_Brick Apr 02 '20 at 23:04
  • Int is faster than Integer. That said, you want to allow large bets and raises of billions of dollars then you need Integer. – hugomg Apr 03 '20 at 15:09