我有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
如何解决问题?
答案 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))
的实例,这就是您收到错误的原因。