Skip to content

Instantly share code, notes, and snippets.

@MichaelBaker
Created June 17, 2014 18:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichaelBaker/916c04cb1d444e29c486 to your computer and use it in GitHub Desktop.
Save MichaelBaker/916c04cb1d444e29c486 to your computer and use it in GitHub Desktop.
Reader Monad Example
import Control.Monad.Reader (runReader, ask)
data Game = Game { playerOne :: String
, playerTwo :: String
, currentValue :: Int
}
data Move = Move { player :: String
, value :: Int
}
-- Argument passing style
makeMove game move bannerText = (game { currentValue = currentValue game - value move}, message)
where message = gameMessage (value move) bannerText
gameMessage value bannerText = bannerText ++ " -> " ++ (show value)
-- Monadic style
makeMoveR game move = do
message <- gameMessageR $ value move
return (game { currentValue = currentValue game - value move}, message)
gameMessageR value = do
bannerText <- ask
return $ bannerText ++ " -> " ++ (show value)
main = do
let game = Game "Michael" "Wai" 10
move = Move "Michael" 2
let (_, firstMoveText) = makeMove game move "Michael making a move"
putStrLn firstMoveText
let (_, firstMoveTextR) = runReader (makeMoveR game move) "Michael making a move"
putStrLn firstMoveTextR
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment