[Haskell-cafe] Making MVar and Chan Instances of Typeable

Benjamin Franksen benjamin.franksen at bessy.de
Fri Nov 5 08:43:55 EST 2004


On Friday 05 November 2004 15:51, you wrote:
> On Fri, Nov 05, 2004 at 01:57:53PM +0100, Benjamin Franksen wrote:
> > Hello Experts,
> >
> > I need MVar and Chan to be instances of Typeable. Any hint on how this is
> > most easily done would be greatly appreciated. I could change the
> > libraries and add 'deriving Typeable' but I hesitate to do so.
>
> The easiest way is to hide type constructor Chan:
>
>   import Control.Concurrent
>   import Data.Generics
>
>   newtype MyChan a = MyChan (Chan a) deriving Typeable
>
> Of course, you can also write the instance for Chan by hand.

This might be the easiest way, but is otherwise inconvenient. I tried to write 
the instances by hand. My first attempt was:

instance Typeable a => Typeable (MVar a) where
  typeOf x =
    mkAppTy (mkTyCon "Control.Concurrent.MVar.MVar") [typeOf (undefined::a)]

but unfortunately this doesn't work. Ghc complains about 

Ambiguous type variable `a1' in the top-level constraint:
      `Typeable a1' arising from use of `typeOf' at Helpers.hs:8

The reason is apparently that inside the definition of typeOf the type 
variable 'a' is not unified with the 'a' from the instance header. I could 
write 

  typeOf (MVar x) =
    mkAppTy (mkTyCon "Control.Concurrent.MVar.MVar") [typeOf y]
    where
      y = undefined `asTypeOf` x

but the doc says that typeOf should be written without evaluating its 
argument, so that is ca be passed 'undefined'.

What I need is a trick that enables me to get at the type of the 'a' in the 
instance header for use inside definition of 'typeOf'.

Ben


More information about the Haskell-Cafe mailing list