Skip to content

Instantly share code, notes, and snippets.

@specdrake
Last active July 3, 2020 10:31
Show Gist options
  • Save specdrake/f680ddad8ead4d7958fb053d719cc6f2 to your computer and use it in GitHub Desktop.
Save specdrake/f680ddad8ead4d7958fb053d719cc6f2 to your computer and use it in GitHub Desktop.
A simple State example in haskell
module Main where
import Control.Monad.Trans.State
import Data.Functor.Identity
type PScore = Int
type CScore = Int
type GameState = (PScore, CScore)
valFromGameState :: GameState -> (Int, Int)
valFromGameState = id
-- 1 for player's point, 2 for computer's point
nextGameState :: Int -> GameState -> GameState
nextGameState ind s = case ind of
1 -> (fst s + 1, snd s)
2 -> (fst s, snd s + 1)
_ -> s
type GameStateMonad = StateT GameState Identity
getNextGameState :: Int -> GameStateMonad (Int, Int)
getNextGameState ind = state $ \st -> let st' = nextGameState ind st in (valFromGameState st', st')
-- In this instance of the game, player scores two points and computer scores one point
oneGame :: GameStateMonad (Int, Int)
oneGame = do
x <- getNextGameState 1
y <- getNextGameState 1
return =<< getNextGameState 2
main = do
-- Final state should be (2, 1)
print (evalState oneGame (0,0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment