[Template-haskell] Deriving Read with Template Haskell (Re: automatic instances for pretty printing and parsing)

Misha Aizatulin avatar at hot.ee
Sat Sep 9 11:31:09 EDT 2006


Johannes Waldmann wrote:

> I use Text.PrettyPrint.HughesPJ and
> Text.ParserCombinators.Parsec heavily so I made
> some DrIFT rules for deriving the "obvious" instances for
>
> class ToDoc  a where toDoc :: a -> Doc
> class Reader a where readerPrec :: Int -> Parser a
>
> Perhaps someone has solved a similar problem before.

  I was looking for the same thing because I didn't like the way derived
instances of Read depend on whether I define my datatypes in prefix,
infix or record form. I ended up writing my own Read derivation using
Template Haskell. Here it is. Basically it can read prefix, infix or
record syntax where applicable. It is based on ReadPrec, not Parsec though.

  Some further notes and questions:

1. Instead of Read I actually use another class, Parse, which is a clone
of Read. The reason is that I wanted to have new instances for some
standard types that already have their Read instances defined. This
introduces some hackery and requires you to use
-fallow-overlapping-instances. If you don't like it, it should be quite
easy to go back to Read.

2. My instance context derivation is very primitive: I simply repeat all
the field types in the context, say

   > data T a b = T1 Int | T2 (a b) (Maybe b)
   > instance (Parse Int, Parse (a b), Parse (Maybe b)) => Parse (T a b)

  The result is that you need -fallow-undecidable-instances to chew
through all that :) Here a question: are there any pitfalls about
writing such instances that I don't currently see?

  Any feedback, improvements, fixes, etc. always welcome!

Cheers,
  Misha
-------------- next part --------------
A non-text attachment was scrubbed...
Name: testDeriveParse.hs
Type: text/x-haskell
Size: 1125 bytes
Desc: not available
Url : http://www.haskell.org//pipermail/template-haskell/attachments/20060909/64abd77e/testDeriveParse.bin
-------------- next part --------------
A non-text attachment was scrubbed...
Name: DeriveParse.hs
Type: text/x-haskell
Size: 5142 bytes
Desc: not available
Url : http://www.haskell.org//pipermail/template-haskell/attachments/20060909/64abd77e/DeriveParse.bin
-------------- next part --------------
A non-text attachment was scrubbed...
Name: Parse.hs
Type: text/x-haskell
Size: 2105 bytes
Desc: not available
Url : http://www.haskell.org//pipermail/template-haskell/attachments/20060909/64abd77e/Parse.bin
-------------- next part --------------
A non-text attachment was scrubbed...
Name: TypeInfo.hs
Type: text/x-haskell
Size: 2123 bytes
Desc: not available
Url : http://www.haskell.org//pipermail/template-haskell/attachments/20060909/64abd77e/TypeInfo.bin


More information about the template-haskell mailing list