这是我试图弄清楚的 State Monad 代码
data State a = State (Int -> (a, Int))
instance Monad State where
return x = State (\c -> (x, c))
State m >>= f = State (\c ->
case m c of { (a, acount) ->
case f a of State b -> b acount})
getState = State (\c -> (c, c))
putState count = State (\_ -> ((), count))
instance Show State where -- doesn't work
show (State a) = show a -- doesn't work
我正在尝试将 State 作为 Show 的实例,以便我可以看到getState
and putState count
在 ghci 提示符下。
任何教程或 State Monad 材料的链接也很好。
这是一个Show
可以帮助了解发生了什么情况的实例:
instance Show a => Show (State a) where
show (State f) = show [show i ++ " => " ++ show (f i) | i <- [0..3]]
然后你可以这样做:
*Main> getState
["0 => (0,0)","1 => (1,1)","2 => (2,2)","3 => (3,3)"]
*Main> putState 1
["0 => ((),1)","1 => ((),1)","2 => ((),1)","3 => ((),1)"]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)