Haskell 类型类层次结构

标签 haskell type-families

我有两门课:

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

我有一个带有类型签名的函数:

 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

如何解决问题?

最佳答案

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

    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)) 的实例,这就是您收到错误的原因。

关于Haskell 类型类层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27471482/

相关文章:

haskell - Cabal 库与 cabal 安装。有什么不同?

haskell - Repa --- 如何制作一个Read实例?

haskell - 无法为关联数据系列派生 Typeable

haskell - 网线的完整示例?

haskell - 为什么运算符/函数转换不可逆?

haskell - 在存在数据族的情况下键入(中)等式

haskell - 关于非单射类型函数的简单类型族示例错误

haskell - Haskell 中的封闭类型族和类型推断

haskell - Vinyl:使用需要所有字段共享约束的函数进行 rtraverse

haskell - FunctionalDependencies 不统一唯一标识的类型