proposal: add 'unsafeCoerce'

Malcolm Wallace Malcolm.Wallace at cs.york.ac.uk
Mon Nov 20 09:45:13 EST 2006


Simon Marlow <simonmarhaskell at gmail.com> wrote:

> >>Now, can we say something portable about these uses?
> 
> I'd like to have a precise (sound, if not complete) description of
> when it's safe to use unsafeCoerce in GHC, but it needs some careful
> thought.

And not just GHC.  I think all the points you mention (below) would be
entirely reasonable for all implementations.

>   * cast that changes a phantom type, or changes a type that is not
>     reflected by a part of the value,
>     eg. 'unsafeCoerce (Left 3) :: Either Int a' should be fine for any
>     'a',
> 
>   * casting a polymorphic type to the actual type of the runtime value.
>     That is, you can safely cast a value to its correct type.  (eg. in
>     Typeable.cast).
> 
>   * casting an unboxed type to another unboxed type of the same size.

There is one more important use case you haven't mentioned:

    * casting from a newtype to the contained value (or vice versa).

This latter type of cast is the only one I can remember ever having used
myself.

Regards,
    Malcolm


More information about the Libraries mailing list