Defining instances of superclasses

Zdenek Dvorak
Mon, 01 Jul 2002 00:36:19 +0000


I've got the following problem:

I have class Structure, that says that its members have some internal parts
that can be read from/written to Strings:

>data StrItem a=forall b c.(Show b,Parse c)=>StrItem String (a->b) (a->c->a)
>class Structure a where
>  strName::a->String
>  strEmpty::a
>  strItems::[StrItem a]

Now I would like to use it to create instances of Show and Parse (and 
others (for input/output from various formats, ...)).

The approaches I have tried:


>instance Structure a => Show a where
>  showsPrec _ w =
>   showsStruct (strName w) (map showsPair strItems)
>  where
>   showsPair (StrItem fName fGet _)=(fName,shows $ fGet w)

This is nice, but it only works in ghc with allowed overlapping and 
instances. It may not seem too important, when I use existential types 
but existential types are supported by at least one more implementation 
and they seem to me to be a well defined extension that has good chances to
become part of standard Haskell later; handling of overlapping and 
instances in ghc seems quite too much ad-hoc and experimental for me.


>newtype Str a=Str a
>instance Structure a => Show (Str a) where
>  showsPrec _ (Str w) =
>   showsStruct (strName w) (map showsPair strItems)
>  where
>   showsPair (StrItem fName fGet _)=(fName,shows $ fGet w)

This seems to be a standard way how to do it. The problem is, that
I don't get Show instance for a, but for isomorphic type Str a; this is
a bit annoying when I want to use it; also I may no longer use deriving Show
on types containing such structure.

Is there some better way how to do this?

Zdenek Dvorak

Send and receive Hotmail on your mobile device: