proposal: add 'unsafeCoerce'

Donald Bruce Stewart dons at
Mon Nov 20 00:42:58 EST 2006

> Hello,
> I think that it is a really bad idea to make 'unsafeCoerce' a part of
> the standard libraries.  As far as I understand, 'unsafeCoerce' is
> only "safe" if the programmer assumes something about the
> representations of values (in particular, that values of different
> types have the same representations).  Haskell makes no such
> guarantees so, by definition, any program that uses 'unsafeCoerce' is
> using an implementation specific extension.  I was trying ot think of
> cases where 'unsafeCoerce' might be somewhat safe, and the main
> example I came up with is when the coersion happens on a phantom type.
> Are there other reasonably portable examples?

Perhaps the implementations of Data.Typeable (assuming the underlying
Typeable stuff was portable):

    cast :: (Typeable a, Typeable b) => a -> Maybe b
    cast x = r
                r = if typeOf x == typeOf (fromJust r)
                    then Just $ unsafeCoerce x
                    else Nothing

Its another case of the programmer having a proof not expressible in the
type system. I suspect there will be more of these in the future as
people write more and more proof/type system preprocessing tools and

-- Don

More information about the Libraries mailing list