Skip to content

Instantly share code, notes, and snippets.

@evancz

evancz/State.hs Secret

Last active August 29, 2015 14:02
Show Gist options
  • Save evancz/7939522fb43814afa9e1 to your computer and use it in GitHub Desktop.
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!
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
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
-- 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