开发者

Why is this declaration not allowed in Haskell?

开发者 https://www.devze.com 2023-04-09 00:56 出处:网络
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 roughl

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 = 开发者_StackOverflow中文版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.


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]).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号