为什么 Haskell 不允许这种声明?

发布于 2024-12-07 01:24:52 字数 331 浏览 1 评论 0原文

我知道 Functor 和 Applicative 应该是 Monad 的超类,但由于历史原因并非如此。但是,为什么不能将 Monad 声明为 Functor 的实例?这将具有大致相同的效果,但无需修改现有代码。如果您尝试这样做,GHC 会抱怨:

instance Functor Monad where
   fmap = liftM

Class `Monad' used as a type
In the instance declaration for `Functor Monad'

这是为什么?这可能是有充分理由的。

I know that Functor and Applicative should be superclasses of Monad, but aren't for historical reasons. However, why isn't is possible to declare Monad an instance of Functor? This would have roughly the same effect, but without having to modify existing code. If you're trying to do this, GHC complains:

instance Functor Monad where
   fmap = liftM

Class `Monad' used as a type
In the instance declaration for `Functor Monad'

Why is that? There's probably a good reason for it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

又怨 2024-12-14 01:24:52

你的语法是错误的。 Monad 是一个类型类,而不是数据类型。您可以编写的是

instance Monad a => Functor a where fmap = liftM

但是,这仅适用于扩展 FlexibleInstances (允许不采用 T a1 a2< 形式的实例/sub> ... an 其中 a1, a2, ... a n 是类型变量,没有上下文)和UndecidableInstances(允许这个特定实例[我不知道为什么需要这个])。

Your syntax is wrong. Monad is a typeclass, not a data type. What you could write is

instance Monad a => Functor a where fmap = liftM

However, this will only work with the extensions FlexibleInstances (permits instances that are not of the form T a1 a2 ... an where a1, a2, ... an are type variables and there is no context) and UndecidableInstances (which permits this specific instance [I don't know why this is needed]).

病女 2024-12-14 01:24:52

原因是 Monad 是一个类型类,而实例声明需要类型或类型构造函数。错误消息清楚地表明了这一点。类型类和类型是两种不同的事物。它们在 Haskell 中永远不可互换。

The reason is that Monad is a type class while an instance declaration requires a type or type constructor. The error message clearly states that. Type classes and type are two distinct kinds of things. They are never interchangable in Haskell.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文