nob*_*ody 2 monads haskell state-monad
这是我试图弄清楚的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
Run Code Online (Sandbox Code Playgroud)
我努力使国家作为展会的实例,这样我可以看到的动作getState,并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]]
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
*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)"]
Run Code Online (Sandbox Code Playgroud)
在Haskell中,类型类只分类相同类型.Monad对类型进行分类* -> *,而Show则对类型进行分类*.你的国家类型有一种* -> *这就是为什么没有你的问题Monad的实例,但有是你的问题Show的实例.State被称为"类型构造函数",因为它使用一种类型来生成另一种类型.可以认为它类似于类型级别的函数应用程序.因此,您可以应用特定类型并创建其实例:
instance Show (State Char) where
show _ = "<< Some State >>"
Run Code Online (Sandbox Code Playgroud)
现在,这不是一个非常有用的实例,尝试类似Sjoerd的建议,以获得更有意义的Show实例.请注意,他的版本使用带约束的泛型类型.
instance (Show a) => Show (State a) where
-- blah blah
Run Code Online (Sandbox Code Playgroud)
泛型类型是a,而约束是(Show a) =>,换句话说,a它本身必须是一个实例Show.