Problem with Data.Dynamic

Glynn Clements glynn.clements@virgin.net
Fri, 25 Oct 2002 10:01:11 +0100


Martin Sj=F6gren wrote:

> I have a problem with Data.Dynamic. The problem is probably that I do=
n't
> understand it. From my understanding, the following program should wo=
rk:
>=20
> -8<------------------------
> import Data.Dynamic
>=20
> data Foo =3D Foo { x :: Int }
>         deriving Show
>=20
> instance Typeable Foo where
>     typeOf _ =3D mkAppTy (mkTyCon "Foo.Foo") []
>=20
>=20
> main =3D do
>     let dynObj =3D toDyn $ Foo 42
>     print dynObj
>     let Just obj =3D fromDynamic dynObj :: Maybe Foo
>     print obj
> -8<------------------------
>=20
> But when I compile it (ghc Foo.hs) and run it (./a.out) I get:
>=20
> <<Foo.Foo>>
>=20
> Fail: Foo.hs:13: Irrefutable pattern failed for pattern (Data.Maybe.J=
ust
> obj)
>=20
> Which indicates that fromDynamic returned Nothing. What is the proble=
m
> here? Do I have to employ special trickery to use Dynamic with record=
s?

You have to ensure that the TyCon is unique. A comment in Dynamic.hs
says:

-- | Builds a 'TyCon' object representing a type constructor.  An
-- implementation of "Data.Dynamic" should ensure that the following ho=
lds:
--
-- >  mkTyCon "a" =3D=3D mkTyCon "a"
--
-- NOTE: GHC\'s implementation is quite hacky, and the above equation
-- does not necessarily hold.  For defining your own instances of
-- 'Typeable', try to ensure that only one call to 'mkTyCon' exists
-- for each type constructor (put it at the top level, and annotate the=

-- corresponding definition with a @NOINLINE@ pragma).

If you use:

=09fooTc =3D mkTyCon "Foo.Foo"
=09
=09instance Typeable Foo where
=09    typeOf _ =3D mkAppTy fooTc []

or compile with "-O", your program works.

--=20
Glynn Clements <glynn.clements@virgin.net>