Reputation: 2098
I want to extend Show type class within my type class and then provide implementation for both of the classes
data XX = XX String --class
class Show a => Test a where
mySh :: a -> String
show :: a -> String
instance Test XX where --implementation for both show and mySh
mySh (XX a) = a
show (XX a) = "---" ++ a
I am getting this error
• No instance for (Show XX)
arising from the superclasses of an instance declaration
• In the instance declaration for ‘Test XX’
I just want Test to inherit Show (without the default implementation) and provide it's own methods.
Upvotes: 1
Views: 183
Reputation: 120751
The subclass relation Show a => Test a
(read: Show
is a superclass of Test
) simply means that any type which is an instance of Test
must also be an instance of Show
, i.e. pretty much exactly what GHC is telling you. To this end, well, write that instance:
instance Show XX where
show (XX a) = "---" ++ a -- please don't implement it this way, `show`
-- is supposed to yield valid Haskell code
instance Test XX where
mySh (XX a) = a
In practice, the Show
class is almost always best instantiated with a simple deriving
statement:
data XX = XX String
deriving (Show)
instance Test XX where
mySh (XX a) = a
What you can not do in Haskell, is “override” the show
method. That's something OO languages do to get a different run-time behaviour on a subtype, which is basically what an OO child class is. Subtype because it contains values that can also be used as values of the parent class. But Haskell does not have subtypes. You may rather think of classes as sets of types, and a subclass of the Show
class is a subset of the set of types which have a Show
instance.
Upvotes: 4