Bet
Bet

Reputation: 404

Haskell type classes hierarchy

I have 2 classes:

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

I have function dosomething with type signature:

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

I define instance of Theme class for data type SimpleTheme:

data SimpleTheme a = SimpleTheme a

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

If in renderTheme I do something with background or foreground, I get compilation error:

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

How to solve problem?

Upvotes: 2

Views: 141

Answers (1)

Cirdec
Cirdec

Reputation: 24166

You can fix that single problem by changing the definition of renderTheme in the SimpleTheme instance. The context only requires that there be a ColorList a instance, not a ColorList (SimpleTheme a), so we can use background on the a held in a SimpleTheme, but can't use background on the whole SimpleTheme.

    renderTheme (SimpleTheme a) = dosomething $ background a

Explanation of the error

From the context

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

We can deduce the following.

  • Since there's a ColorList a there must be what is required for a ColorList. That is, there's a type ColorType a and an instance IsColor (ColorType a).
  • Since there's a ColorList (ThemeColorList (SimpleTheme a)) there must be what is required for a ColorList. that is, there's a type ColorType (ThemeColorList (SimpleTheme a)) and an instance IsColor (ThemeColorList (SimpleTheme a)).

None of these is an instance for IsColor (ColorType (SimpleTheme a)), which is why you get the error.

Upvotes: 2

Related Questions