Re : escape from existential quantification
Wang Meng wrote
I understand that existentially bound types cannot escape.
For example, say we have data Foo = forall a. Foo Int a
Then we cannot define a function extract (Foo i a) = a
However,this limitation makes it extremly difficult to program with local quantifications.Is there any way to by pass this? It occasionally happens that I *know* what type is (or at least ought to be) inside an existential type, but unfortunately GHC doesn't, and I need to get the value out. This can be solved using dynamic types, for example you declare the datatype as
data Foo = forall a. Typeable a => Foo Int a
(or something like that), then you can extract the a value by going to Dynamic and back.
It occasionally happens that I *know* what type is (or at least ought to be) inside an existential type, but unfortunately GHC doesn't, and I need to get the value out. This can be solved using dynamic types, for example you declare the datatype as
You can also use an unsafe cast operation if you know statically what the type will be, but the compiler doesn't. See for example http://www.isi.edu/~hdaume/haskell/NewBinary/TestBits.hs for an example of this. It essentially has a function which writes items of arbitrary type (in a list) to a binary memory location and then reads the back. When reading them back, the only way to know the type is to look at the type of the corresponding item on the "write" list. It relies on this to make the casting really a safe operation.
participants (2)
-
George Russell -
Hal Daume III