[英]Understanding Type Parameters in Typeclass Declarations
I'm having a bit of trouble understanding what the type parameters indicate in the case of the State monad, but also for the other mtl monads as well. 我在理解状态monad的情况下类型参数指示的内容时遇到了一些麻烦,而且对于其他mtl monad也是如此。 Insofar as I understand it, when I compose a State monad, as in
State String Int
, what I really have is StateT String Identity Int
. 就我所理解的那样,当我
StateT String Identity Int
State monad时,就像在State String Int
,我真正拥有的是StateT String Identity Int
。 In the case of the method get
for the MonadState
typeclass, it returns ms
, what is the 'm' in this case? 对于
MonadState
类型类的get
方法,它返回ms
,在这种情况下'm'是什么? Is it the Identity monad, Identity Int? 它是Identity monad,Identity Int吗? And in this case is the 's' which represents the type of the state a parameter to the 'm'?
在这种情况下,'s'表示状态的类型是'm'的参数?
Thank you, I'm obviously having a bit of trouble understanding Haskell's type system. 谢谢,我显然在理解Haskell的类型系统时遇到了一些麻烦。
Well it depends on what instance you use – that's the whole point of the type class! 那么它取决于你使用的实例 - 这是类型类的全部要点!
class MonadState s m where
get :: m s
In case of simply State
, that's the monad you're in: 如果只是
State
,那就是你所在的monad:
instance MonadState String (State String) where
get :: State String String
...which is short for ...这是短的
instance MonadState String (StateT String Identity) where
get :: (StateT String Identity) String
OTOH, it could also be OTOH,它也可能
instance MonadState Int (StateT Int IO) where
get :: StateT Int IO Int
If we look at the definition of StateT
: 如果我们看一下
StateT
的定义:
class (Monad m) => MonadState s m | m -> s where
get :: m s
put :: s -> m ()
Which has an instance for StateT
defined as 其中
StateT
的实例定义为
instance (Monad m) => MonadState s (StateT s m) where
get = StateT.get
put = StateT.put
Then we say that 然后我们说
type State s a = StateT s Identity a
then we know that in this case, m ~ Identity
. 那么我们知道在这种情况下,
m ~ Identity
。 For your case of State String Int
, we can also infer that s ~ String
and a ~ Int
, so the type of get
is Identity String
and the type of put
is Identity ()
. 对于
State String Int
,我们也可以推断出s ~ String
和a ~ Int
,因此get
的类型是Identity String
, put
的类型是Identity ()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.