2017-10-14 51 views
1

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提取它,无论实例是什么。

回答

3

我们的目标是为包括注型家庭的一些数据结构B的实例,并使用noteOf b键提取它

这不是类型的家庭是如何工作的。您刚才所说的是,您可以通过类型函数Note将由变量a表示的一种类型映射到另一种类型。这并不意味着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