State 和其他 MTL monad 的应用实例?
查看 Control 的文档。应用性
,我注意到它们有某些单子的实例声明(例如IO
、Maybe
,尤其是ST
) ,但是有没有 MTL monad 的实例,例如 State
和 RWS
。相反,它看起来像是一个通用的 WrappedMonad
类型定义,我猜它是为了涵盖所有其他情况。
所以我的问题是:
为什么 MTL monad 没有
Applicative
实例?到目前为止,我自己找到的最好答案是一个三岁的孩子帖子,其中有人实现了这些实例,但被立即忽略。WrappedMonad 是怎么回事?我在 Reddit 上发现了一篇 Reddit 上的帖子,简要解释了这一点,但是我想我对如何使用它感到困惑。
最终我希望能够以应用风格使用 State
(就像 向我推荐),但如果我必须在代码中使用 WrappedMonad
数据构造函数,那么这似乎并不是一个胜利。我还可以完全忽略 WrappedMonad
,并以与 IO
、ST
相同的方式自己定义 Applicative
实例> 等等:就 return
和 ap
而言...但这似乎也很愚蠢。
Looking at the docs for Control.Applicative
, I notice that they have instance declarations for certain monads (e.g. IO
, Maybe
and notably ST
), but there are no instances for MTL monads such as State
and RWS
. Instead it looks like there's a general-purpose WrappedMonad
type defined, which I'm guessing is to cover all other cases.
So here are my questions:
Why aren't there
Applicative
instances for MTL monads? The best answer I've been able to find on my own so far is a three year old post, where somebody implemented these instances and was summarily ignored.What's the deal with
WrappedMonad
? I found a post on Reddit that explains it briefly, but I think I'm confused about how to use it.
Ultimately I'd like to be able to use State
in an applicative style (as was recommended to me), but if I have to litter my code with WrappedMonad
data constructors then it doesn't seem like a win. I could also ignore WrappedMonad
entirely, and define the Applicative
instance myself the same way that was done for IO
, ST
and so on: in terms of return
and ap
... But that seems goofy as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该文档仅根据
base
包的内容生成,该包不包含State
- 因此它不包含Applicative
实例。如果您查看 MTL 文档,您将看到列出的Applicative
实例。或者,您可以打开 GHCi,导入 Control.Monad.State 和 Control.Applicative,然后使用
:i Applicative
列出Applicative
或:i 的实例StateT
列出StateT
具有实例的类(State
是StateT
的类型别名,其参数之一是固定的) 。任何一个都将表明确实存在这样的例子。That documentation is generated based solely on the contents of the
base
package, which does not containState
- so it does not containApplicative
instances for it. If you look in the MTL documentation, you'll see anApplicative
instance listed.Alternately, you can open up GHCi, import Control.Monad.State and Control.Applicative, and use
:i Applicative
to list the instances ofApplicative
or:i StateT
to list the classes for whichStateT
has instances (State
is a type alias forStateT
with one of its parameters fixed). Either will show that there is indeed such an instance.mtl monad 的 Applicative 实例无法在基础文档中列出,因为此时没有可用的 mtl。好消息是 mtl 有 Applicative 实例 StateT 例如,从 mtl-2.0.0.0 开始。
The Applicative instances for the mtl monads can't be listed in the base docs, because there's no mtl available at that point. The good news is that mtl has Applicative instances StateT for example, since mtl-2.0.0.0.