在Haskell中,状态是单子传递并存储状态。在下面的两个例子中,都使用
然而,这似乎不太直观。那么,这是否意味着当我想传递State单子时,只需要
非常感谢!
>>
传递State单子,并通过函数内联和还原进行了密切验证,确保状态确实传递到了下一步。然而,这似乎不太直观。那么,这是否意味着当我想传递State单子时,只需要
>>
(或者>>=
和lambda表达式\s -> a
,其中s
不是a
的自由变量)?有人可以提供一个直观的解释吗,而不必去简化函数吗?-- the first example
tick :: State Int Int
tick = get >>= \n ->
put (n+1) >>
return n
-- the second example
type GameValue = Int
type GameState = (Bool, Int)
playGame' :: String -> State GameState GameValue
playGame' [] = get >>= \(on, score) -> return score
playGame' (x: xs) = get >>= \(on, score) ->
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
非常感谢!