【发布时间】:2012-09-20 15:36:06
【问题描述】:
我正在尝试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
【问题讨论】:
-
我建议至少为顶级函数编写显式类型签名,也许还可以为您不确定类型的任何其他术语编写显式类型签名。它有助于定位错误,并了解类型系统如何更好地工作。
标签: haskell state monads composition