[Haskell] Incoherent instances can make ST monad unsound

Thomas Jäger thjaeger at gmail.com
Fri Jan 27 02:18:19 EST 2006

On Thu, 2006-01-26 at 20:29 -0800, oleg at pobox.com wrote:
> circumstances, many things break, including the ST monad. One can
> indeed break the essential guarantee of the ST monad -- for example,
> create a top level STRef *and* fruitfully use in arbitrary ST
> computations. The enclosed code does exactly that. Thus,
> unsafePerformST becomes expressible in Haskell, given enough
> features. The presence of top-level mutable cells breaks the
> referential transparency. Hopefully the authors of Haskell' and
> Haskell2 would attach all-upper-case warnings to these extensions.

I don't think this is the extensions' fault; the problem is rather a
bogus Typeable instance which basically gives you unsafeCoerce#. In
fact, the code below compiles without any extensions and also breaks
pretty much every static guarantee.

import Data.Typeable
import Data.Dynamic

newtype Foo a = Foo { runFoo :: a ()}
newtype Const a b = Const { runConst :: a }

instance Typeable (Foo a) where
  typeOf _ = mkTyConApp (mkTyCon "Anything goes") []

coerce :: a -> b
coerce = runConst . runFoo . flip fromDyn undefined . toDyn . Foo .Const

More information about the Haskell mailing list