我有两门课:
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
>aSimpleTheme
中,但不能在整个 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/