Generics

Simon Peyton-Jones simonpj@microsoft.com
Thu, 5 Oct 2000 08:54:02 -0700


Folks,

I've added Hinze/PJ-style generic class definitions to GHC, based
on summer hacking done by Andrei Serjantov.  The design is based
very closely on the Haskell workshop 2000 paper
	http://www.informatik.uni-bonn.de/~ralf/Derive.ps.gz

For example:

  class Bin a where
    toBin   :: a -> [Int]
    fromBin :: [Int] -> (a, [Int])
  
    toBin {| Unit |}    Unit	= []
    toBin {| a :+: b |} (Inl x)   = 0 : toBin x
    toBin {| a :+: b |} (Inr y)   = 1 : toBin y
    toBin {| a :*: b |} (x :*: y) = toBin x ++ toBin y
  
  
    fromBin {| Unit |}    bs        = (Unit, bs)
    fromBin {| a :+: b |} (0:bs)  = (Inl x, bs')    where (x,bs') = fromBin
bs
    fromBin {| a :+: b |} (1:bs)  = (Inr y, bs')    where (y,bs') = fromBin
bs
    fromBin {| a :*: b |} bs  	   = (x :*: y, bs'') where (x,bs' ) =
fromBin bs
					        (y,bs'') = fromBin bs'

Now we can say simply

  	instance Bin a => Bin [a]

and the compiler will derive the appropriate code automatically.


This is now implemented and documented in the CVS version of GHC,
and will be in every future version of GHC.  (But I'm afraid we don't plan 
a binary release for a while.)  

At present we don't (alas) support constructor and field names, so you
can't implement Read and Show generically.  But I thought it was worth
getting committed what *is* done.

Simon