[Haskell-cafe] Dynamic types through unsafeCoerce

Brandon Moore brandonm at yahoo-inc.com
Tue Dec 12 20:07:25 EST 2006

Alfonso Acosta wrote:
> Ok, instead of pushing about why I want to use unsafeCoerce (which I
> know it's not a good thing) I decided (as suggested by Taral) to paste
> a simplified example of my code.
> If anyone finds a way of implementing something equivalent to this 
> code without
> unsafeCoerce#  and ...

It looks to me like the C code could make your program segfault from a 
type missmatch, if it
gets a handle from instantiating one descriptor, and tries to run it 
from another.
Building code which can fail that way hopefully requires unsafeCoerce!

I think Udo's code is the best way to go, if it solves your problem.
Udo's code is equivalent to code similar to yours but defined around the 
existential type

data Descriptor =
    forall hd . Descriptor { -- create a new instance and return its 
                instantiate            :: InstanceInitData -> hd,
                -- Run and return a new handler
                run                    :: hd   -> IO hd}

Then observing that because hd is hidden you can only use an hd by 
passing it run, so you
might as well wrap it up in that Runner type.

If you want to be able to define several Descriptors over the same type 
hd, and trade handles
back and forth between their run functions, then you will need some 
casting (but tools from
Typeable and Dynamic should be enough, without bringing unsafeCoerce)


More information about the Haskell-Cafe mailing list