[Haskell-cafe] why cannot i get the value of a IORef variable ?

Derek Elkins derek.a.elkins at gmail.com
Thu Oct 22 17:39:48 EDT 2009


On Thu, Oct 22, 2009 at 1:32 PM, David Menendez <dave at zednenem.com> wrote:
> On Thu, Oct 22, 2009 at 2:23 AM, Gregory Crosswhite
> <gcross at phys.washington.edu> wrote:
>> For clarity, one trick that uses "unsafePerformIO" which you may have seen
>> posted on this list earlier today is the following way of creating a
>> globally visible IORef:
>>
>> import Data.IORef
>> import System.IO.Unsafe
>>
>> *** counter = unsafePerformIO $ newIORef 0 ***
>
> Danger! If the monomorphism restriction is disabled, this ends up
> creating a value of type forall a. Num a => IORef a, which can be used
> to break type safety.
>
> More generally,
>
> cell :: IORef a
> cell = unsafePerformIO $ newIORef undefined
>
> unsafeCoerce :: a -> b
> unsafeCoerce x = unsafePerformIO $ do
>    writeIORef cell x
>    readIORef cell
>
> This way lies segmentation faults. That "unsafe" is there for a reason.

This is exactly what happened in the original example.


More information about the Haskell-Cafe mailing list