如何使用类型族定义类

时间:2017-10-14 17:10:12

标签: haskell

The following code生成"预期约束"错误:

{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ExistentialQuantification #-}

type family Note a
type instance Note String = String

data SomeNote = forall a. Note a => SomeNote a

class HasNote b where
  noteOf :: b -> SomeNote

错误为Expected a constraint, but 'Note a' has kind '*', in the definition of SomeNote。为什么?我该如何解决?

目标是在某些数据结构b中包含Note类型族的实例,并使用noteOf b提取它,无论实例是什么。

1 个答案:

答案 0 :(得分:3)

目标是在某些数据结构b中包含Note类型系列的实例,并使用noteOf b提取它

那不是家庭类型的工作方式。您真正说的是,您可以通过类型函数a将一个由变量Note表示的类型映射到另一个类型。它并不意味着a类型的值包含类型Note b的值。类型类强烈暗示Note a类型在a类型内或可由type family Note a type instance Note String = String class SomeNote a where noteOf :: a -> Note a 类型计算。

代码如下:

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}

class SomeNote a where
    type Note a :: *
    noteOf :: a -> Note a

instance SomeNote String where
    type Note String = String
    noteOf = id

更好的是,请考虑使用相关类型:

{{1}}
相关问题