Last active
July 3, 2020 10:31
-
-
Save specdrake/f680ddad8ead4d7958fb053d719cc6f2 to your computer and use it in GitHub Desktop.
A simple State example in haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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