问题 `Typeable(* - > Constraint)Monoid`实例的目的是什么?


自GHC 7.8起, Typeable 是多重的。看一下内置列表 Typeable 实例 在文档中,我注意到有趣的事情:

Typeable ((* -> *) -> Constraint) Alternative
Typeable ((* -> *) -> Constraint) Applicative
Typeable (* -> Constraint) Monoid

显然,它允许查看(某些)类型的类型表示 Constraint

Prelude Data.Monoid Data.Typeable> typeRep $ (Proxy :: Proxy (Monoid Int))
Monoid Int

这个功能有什么用途,还是只是意外提供?


3150
2018-04-24 19:14


起源



答案:


好, ConstraintKinds现在被允许了。这意味着您可以定义通过约束参数化的数据类型。

一个(人为的)例子:

data CPair (c :: * -> Constraint) where
  MkCPair :: (c a, c b) => a -> b -> CPair c

这是一对可能不同类型的两个组件,它们共享一个公共类:

aPair :: CPair Show
aPair = MkCPair 'x' True

现在,我们想要吗? aPair 成为 Typeable?这需要两者 CPair 和 Show 至 是 Typeable 同样。

deriving instance Typeable CPair
deriving instance Typeable Show

现在:

GHCi> typeOf aPair
CPair Show

所以这只是导致的结果 Typeable 对于类,如果它们现在可以作为类型出现。

有趣的是 Typeable Show 不是预定义的,但是 Typeable Applicative 是。这是因为有一个新的GHC扩展 AutoDeriveTypeable 这似乎在某些模块中启用,但在其他模块中没有启用。同 AutoDeriveTypeable, 有 Typeable 为模块中的所有内容派生的实例,包括类。


10
2018-04-24 23:05