问题描述
这是我要弄清楚的State Monad代码
This is the State Monad code I am trying to figure out
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的实例,以便在ghci提示符下看到getState
和putState count
的动作.
I am trying to make State as instance of Show so that I can see the action of getState
and putState count
on the ghci prompt.
任何教程或指向State Monad资料的链接也将很好.
Any tutorial or link to State Monad material would be nice too.
推荐答案
在Haskell中,类型类仅对相同种类的类型进行分类. Monad对类型为* -> *
的类型进行分类,而Show对类型为*
的类型进行分类.您的State类型的类型为* -> *
,这就是为什么您的Monad
实例没有问题,但您的Show
实例却有问题 的原因. State
之所以称为类型构造函数",是因为它消耗一个类型以产生另一个类型.可以认为它在类型级别上类似于函数应用程序.因此,您可以应用特定的类型并为其创建实例:
In Haskell, typeclasses classify only types of the same kind. Monad classifies types of kind * -> *
, while Show classifies types of kind *
. Your State type has kind * -> *
which is why there isn't a problem with your Monad
instance, but there is a problem with your Show
instance. State
is called a "type constructor" because it consumes a type in order to produce another type. Think of it sort of like function application at the type level. You can therefore apply a specific type and make instances of that:
instance Show (State Char) where
show _ = "<< Some State >>"
现在,这不是一个非常有用的实例,请尝试使用Sjoerd的建议来获得更有意义的Show实例.请注意,他的版本使用带有约束的通用类型.
Now, this isn't a very useful instance, try something like Sjoerd's suggestion to get a more meaningful Show instance. Notice that his version uses a generic type with a constraint.
instance (Show a) => Show (State a) where
-- blah blah
通用类型为a
,约束为(Show a) =>
,换句话说,a
本身必须是Show
的实例.
The generic type is a
, and the constraint is (Show a) =>
, in other words, a
itself must be an instance of Show
.
这篇关于“实例显示状态"不编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!