[Haskell] Deferred instance declarations (serialization ofexistential boxes)

Simon Peyton-Jones simonpj at microsoft.com
Mon Sep 25 06:27:05 EDT 2006


[redirecting to GHC users, since it's a GHC-specific question]

Misha

|   I asked this question on haskell-cafe once, but my post didn't get any
| responses, so I try once again here explaining a bit more where my
| problem comes from.

I was at ICFP.

|   Suppose I have a monomorphic datatype, say T and want to do something
| with it, which depends on an instance of class C being defined for T.
| However I can only provide this instance later, in a different module.
| So I would like to write something like
| 
| > f :: C T => T -> T
| or
| > instance C T => C T' where
| > -- a body that uses functions from C T

There is no reason in principle why this isn't ok.  But there is a practical reason why things are the way they are.  Generally, GHC tries to share constraints as much as possible, so that a (C T) constraint in one function right hand side is satisfied by the same binding as another (C T) constraint from another right hand side.  So in general, GHC "floats" constraints outwards if they don't mention any type variables bound by the forall's of the type signature.

The whole question of the interaction of type signatures and constraints is quite delicate, and I rather doubt I'll change this behaviour soon.  (And no one else has asked for it before, I think.)  But I think the case is stronger for top-level constraints, and I will bear it in mind.  If you would like to open a Trac feature request, please do so.


Concerning your application

|   I am having a box like
| > data Box = forall a. Cxt a => Box a
|   and want to write a Read instances for it.

I don’t see how it helps to defer the Read instance.  Reading existentials is bound to be difficult, or even impossible.  I guess it depends what is in Cxt.

Simon


More information about the Glasgow-haskell-users mailing list