Problem with Data.Dynamic
Hello list. I have a problem with Data.Dynamic. The problem is probably that I don't understand it. From my understanding, the following program should work: -8<------------------------ import Data.Dynamic data Foo = Foo { x :: Int } deriving Show instance Typeable Foo where typeOf _ = mkAppTy (mkTyCon "Foo.Foo") [] main = do let dynObj = toDyn $ Foo 42 print dynObj let Just obj = fromDynamic dynObj :: Maybe Foo print obj -8<------------------------ But when I compile it (ghc Foo.hs) and run it (./a.out) I get: <<Foo.Foo>> Fail: Foo.hs:13: Irrefutable pattern failed for pattern (Data.Maybe.Just obj) Which indicates that fromDynamic returned Nothing. What is the problem here? Do I have to employ special trickery to use Dynamic with records? I'm using ghc 5.04, as packaged by Debian. Regards, Martin Sjögren
Rewrite this definition:
instance Typeable Foo where typeOf _ = mkAppTy (mkTyCon "Foo.Foo") []
like this:
instance Typeable Foo where typeOf _ = mkAppTy fooFooTc [] fooFooTc = mkTyCon "Foo.Foo"
The problem is caused by a very dubious optimization used in the representation of TyCons whcih really ought to be fixed. -- Alastair Reid alastair@reid-consulting-uk.ltd.uk Reid Consulting (UK) Limited http://www.reid-consulting-uk.ltd.uk/alastair/
Martin Sjögren wrote:
I have a problem with Data.Dynamic. The problem is probably that I don't understand it. From my understanding, the following program should work:
-8<------------------------ import Data.Dynamic
data Foo = Foo { x :: Int } deriving Show
instance Typeable Foo where typeOf _ = mkAppTy (mkTyCon "Foo.Foo") []
main = do let dynObj = toDyn $ Foo 42 print dynObj let Just obj = fromDynamic dynObj :: Maybe Foo print obj -8<------------------------
But when I compile it (ghc Foo.hs) and run it (./a.out) I get:
<<Foo.Foo>>
Fail: Foo.hs:13: Irrefutable pattern failed for pattern (Data.Maybe.Just obj)
Which indicates that fromDynamic returned Nothing. What is the problem here? Do I have to employ special trickery to use Dynamic with records?
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 holds: -- -- > mkTyCon "a" == 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: fooTc = mkTyCon "Foo.Foo" instance Typeable Foo where typeOf _ = mkAppTy fooTc [] or compile with "-O", your program works. -- Glynn Clements <glynn.clements@virgin.net>
participants (3)
-
Alastair Reid -
Glynn Clements -
Martin Sjögren