繁体   English   中英

智能构造函数类型可以有多个有效的 Functor 实例吗?

[英]Can smart-constructor types have multiple valid Functor instances?

关于Functor的以下两条规则是众所周知的:

  1. 如果类型参数以逆变方式出现,则无法制作Functor
  2. 任何类型最多有一个有效的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM