Haskell类型的层次结构

时间:2014-12-14 16:40:22

标签: haskell type-families

我有2个班级:

class (IsColor (ColorType a)) => ColorList a where
    type ColorType a :: *
    foreground :: a -> (ColorType a)
    background :: a -> (ColorType a)

class (ColorList (ThemeColorList a)) => Theme a where
    type ThemeColorList a :: *
    renderTheme :: a -> b

我有类型签名的函数dosome:

 dosomething :: (IsColor a) => a -> Int

我为数据类型SimpleTheme定义Theme类的实例:

data SimpleTheme a = SimpleTheme a

instance (ColorList a) => Theme (SimpleTheme a) where
    type ThemeColorList (SimpleTheme a) = a
    renderTheme theme = dosomething $ background theme

如果在renderTheme中我使用背景或前景做某事,我会收到编译错误:

Could not deduce (IsColor (ColorType (SimpleTheme a)))
      arising from a use of ‘dosomething’
    from the context (ColorList (ThemeColorList (SimpleTheme a)),
                      ColorList a)
      bound by the instance declaration at

如何解决问题?

1 个答案:

答案 0 :(得分:2)

您可以通过更改renderTheme实例中SimpleTheme的定义来解决该问题。上下文只要求ColorList a个实例,而不是ColorList (SimpleTheme a),因此我们可以在background中保留的a上使用SimpleTheme,但可以&在整个background上使用SimpleTheme

    renderTheme (SimpleTheme a) = dosomething $ background a

错误说明

从上下文

(ColorList (ThemeColorList (SimpleTheme a)),
 ColorList a)

我们可以推断出以下内容。

  • 由于ColorList a必须有ColorList所需的内容。也就是说,类型为ColorType a,实例为IsColor (ColorType a)
  • 由于ColorList (ThemeColorList (SimpleTheme a))必须有ColorList所需的内容。也就是说,类型ColorType (ThemeColorList (SimpleTheme a))和实例IsColor (ThemeColorList (SimpleTheme a))

这些都不是IsColor (ColorType (SimpleTheme a))的实例,这就是您收到错误的原因。