-
-
Save evancz/7939522fb43814afa9e1 to your computer and use it in GitHub Desktop.
an example from this page (http://www.haskell.org/haskellwiki/State_Monad) that I think is quite weak because it's easy to do by just folding over the string... But for the sake of comparison here we are!
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
playGame :: String -> State GameState GameValue | |
playGame [] = do | |
(_, score) <- get | |
return score | |
playGame (x:xs) = do | |
(on, score) <- get | |
case x of | |
'a' | on -> put (on, score + 1) | |
'b' | on -> put (on, score - 1) | |
'c' -> put (not on, score) | |
_ -> put (on, score) | |
playGame xs |
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
playGame : [Char] -> State GameState GameValue | |
playGame chars = | |
case chars of | |
[] -> with state | |
let (_, score) <- get | |
return score | |
c::cs -> with state | |
let (on, score) <- get | |
case c of | |
'a' -> if on then put (on, score + 1) else return () | |
'b' -> if on then put (on, score - 1) else return () | |
'c' -> put (not on, score) | |
_ -> return () | |
playGame cs |
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
-- introduces noOp and when to make "return ()" feel less weird | |
noOp : State s () | |
noOp = return () | |
when : Bool -> State s () -> State s () | |
when b cmd = if b then cmd else return () | |
playGame : [Char] -> State GameState GameValue | |
playGame chars = | |
case chars of | |
[] -> with state | |
let (_, score) <- get | |
return score | |
c::cs -> with state | |
let (on, score) <- get | |
case c of | |
'a' -> when on (put (on, score + 1)) | |
'b' -> when on (put (on, score - 1)) | |
'c' -> put (not on, score) | |
_ -> noOp | |
playGame cs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment