我正在尝试http://www.haskell.org/haskellwiki/State_Monad#Complete_and_Concrete_Example_1给出的示例
这如何使解决方案可组合超出了我的理解。这是我尝试过的,但我得到如下编译错误:
Couldn't match expected type `GameValue -> StateT GameState Data.Functor.Identity.Identity b0'
with actual type `State GameState GameValue'
In the second argument of `(>>=)', namely `g2'
In the expression: g1 >>= g2
In an equation for `g3': g3 = g1 >>= g2
Failed, modules loaded: none.
这是代码:请参阅最后几行
module StateGame where
import Control.Monad.State
type GameValue = Int
type GameState = (Bool, Int)
-- suppose I want to play one game after the other
g1 = playGame "abcaaacbbcabbab"
g2 = playGame "abcaaacbbcabb"
g3 = g1 >>= g2
m2 = print $ evalState g3 startState
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
startState = (False, 0)
main str = print $ evalState (playGame str) startState