Violating memory safety with Haskell's value restriction
Published on: 2025-06-19 12:42:03
Violating memory safety with Haskell's value restriction
A common issue in impure ML-style languages with polymorphism and mutable references is the possibility of polymorphic references.
In a hypothetical impure language that had both these features, but no mitigations against polymorphic references, the following code would be extremely unsafe.
unsafeCoerce :: a -> b = unsafeCoerce x let dangerous = ref Nothing dangerousref := Just x dangerous case dangerous of dangerous Nothing -> error "unreachable" Just y -> y
This code creates a reference dangerous with an initial value of Nothing , writes x to it, and then reads from it again. But because this language doesn’t prevent polymorphic references and Nothing has type forall a. Maybe a , dangerous is actually generalized to forall a. Ref (Maybe a) . This means that in the line that writes to it, dangerous is instantiated to Maybe a , whereas in the line that reads from it, it is instantiated to Maybe b , although the value stored i
... Read full article.