Created
June 17, 2014 18:16
-
-
Save MichaelBaker/916c04cb1d444e29c486 to your computer and use it in GitHub Desktop.
Reader Monad Example
This file contains 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
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