【问题标题】:How to create typeclass instances of a promoted type?如何创建提升类型的类型类实例?
【发布时间】:2012-04-24 03:33:18
【问题描述】:

我有一个通过 ghc 7.4.1 中的 DataKinds 提升的数据类型,以及一个我想用来执行特定类型操作的给定类型类。

data Type = TInt32 | TInt64 | TInt16
class TypeTraits a where
  ...

然后我尝试像这样创建提升类型的类型类实例:

instance TypeTraits TInt32 where
  ...

我收到以下类型的错误:

Kind mis-match
The first argument of `TypeTraits' should have kind `*',
but `TInt32' has kind `Type'
In the instance declaration for `TypeTraits TInt32'

试图通过指定“a”的种类来解决这个问题:

class TypeTraits (a :: Type) where
  ...

Kind mis-match
Expected kind `ArgKind', but `a' has kind `Type'
In the type `a -> String'
In the class declaration for `TypeTraits'

【问题讨论】:

  • 您究竟能在... 区域中添加什么? TInt32 不是可居住的类型,因此它不能在值位置单独使用a。我猜像crazyThing :: TypeTraits a => SomeTypeConstructor a?我很难想象这样的东西会如何有用,但如果我真的伸展,我可以想象它是有用的不知何故。也许吧。
  • 这个想法是为每个实例设置特征。所以我不是在寻找值,而只是一个用于指定类型类的占位符,因此我想在那里选择的函数。例如:class TypeTraits (a :: Type) where type HType a sizeOf :: Proxy a -> Int

标签: haskell typeclass


【解决方案1】:

问题出在类的主体上;具有提升类型的类型没有任何值,因此您不能拥有将一个作为参数的函数。您必须使用 @987654321@ a -> String 或类似名称。

顺便说一句,如果您打开PolyKinds 扩展,那么您应该可以完全省略 kind 注释。 (实际上,您可能必须这样做,才能定义自己的Proxy 类型,因为我认为来自Data.Proxy 的可能是* -> *,而您需要Type -> *。如果您使用@987654329 定义data Proxy p = Proxy @ on,则推断为AnyK -> *。)

【讨论】:

  • paper 中的 Proxy 数据类型终于有意义了,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-10
  • 2016-12-05
  • 2012-08-30
  • 1970-01-01
  • 1970-01-01
  • 2021-05-22
  • 1970-01-01
相关资源
最近更新 更多