Extensible Serialization class with type classes

Simon David Foster s.d.f at btinternet.com
Thu Aug 26 15:19:03 EDT 2004

I've been trying to put together a type-class based serialization (XML)
for types in GHC. Essentially the serializer class takes the form

class Seriliazer a where
   serialize :: a -> XmlFilter

This works very well, but I then wanted to make this system extensible,
so that for example for types which are also typed by equivalent XSD
Types (i.e. types with constraint XSDType a => a) could have their
type-data encoded into the tree. 

The problem is, it seems to me there is no viable method of adding an
extra parameter function to the serialiaze function, which will enforce
extra constraints on a and allow recursive serialization. Obviously
simply passing a function (C a => a -> XmlFilter) doesn't work, since
the type a becomes unified to the top-level type and so can't be passed

The second attempt was to add another type class called Hook, with two
type variables; the first being a dummy type and the second the variable
to represent the type being serialized;

class Hook a t where
    hookAttr :: t -> a -> [(String, String)]
    hookElem :: t -> a -> [XmlFilter]

and rewriting serialize as 

class Hook a t => Serializer a t where
    serialize :: t -> a -> XmlFilter

Then, passing the dummy type to the serialized function as the t value
would force the extra constraints from its Hook instance on a. This
method though doesn't really work that well; first of all it requires
undecidable-instances and second each new instance on serialize requires
a humongous context since each type used directly and indirectly needs
inferring as an instance of Hook. The idea was that this code could be
generated automatically, and that really makes it too difficult to do.

The Third attempt was to use existential types to encapsulate a
constrained polymorphic type and use Typeable + Generics to choose
between a number of functions. This though doesn't work either, since
each value down the type tree needs to be of the appropriate monomorphic
existentially quantified type since polymorphic types aren't Typeable.

I seem to have pretty much exhausted every option for building this
extensible Serializer, and so my question is this; is there anyway of
passing a hook function to the serializer class instances, such that it
will remain polymorphic down the serialization tree but will also
enforce the constraints on the input parameter on the type being
serialized. For example is it every likely to be possible to reify
polymorphic types?


More information about the Glasgow-haskell-users mailing list