
[英]What are the situations when you can/cannot have a Functor instances for a datatype?
[英]Can smart-constructor types have multiple valid Functor instances?
关于Functor
的以下两条规则是众所周知的:
Functor
Functor
实例但如果你稍微作弊,你就可以打破第一条规则。 以休斯列表为例:
data HList a = UnsafeHList ([a] -> [a])
pattern HList a <- UnsafeHList (($ []) -> a)
where HList a = UnsafeHList (a ++)
instance Functor HList where
fmap f (HList a) = HList (map f a)
-- instances necessary to make HList useful, but irrelevant to this example, have been omitted
只要您假设所有HList
都将通过智能构造函数生成,那么Functor
实例是合法的,即使a
出现逆变。
我的问题:你可以使用类似的技术来打破第二条规则吗? 如果您假设它们总是通过智能构造函数生成,是否有任何类型具有两个不同的有效Functor
实例?
绝对地。 假设你有
newtype Foo a = Foo Bool
mkFoo = Foo True
这是它的两个Functor
实例:
instance Functor Foo where
fmap _ (Foo x) = Foo x
instance Functor Foo where
fmap _ !_ = mkFoo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.