[Haskell-cafe] Re: Beginner: IORef constructor?

Bernie Pope bjpop at csse.unimelb.edu.au
Wed Dec 6 01:40:38 EST 2006


On 05/12/2006, at 1:00 PM, Benjamin Franksen wrote:

> Bernie Pope wrote:
>> If you want a global variable then you can use something like:
>>
>>     import System.IO.Unsafe (unsafePerformIO)
>>
>>     global = unsafePerformIO (newIORef [])
>>
>> But this is often regarded as bad programming style (depends who you
>> talk to).
>
> Besides, isn't this example /really/ unsafe? I thought, at least  
> the IORef
> has to be monomorphic or else type safety is lost?

Perhaps your question is rhetorical, but in case it is not, then yes,
we ought to make it a monomorphic type.

This little example seg-faults on my mac, and no doubt on other  
machines as
well:

    import System.IO.Unsafe (unsafePerformIO)
    import Data.IORef

    global = unsafePerformIO (newIORef [])

    main = do
       modifyIORef global (id :)
       x <- readIORef global
       print ((head x + 1) :: Int)

It writes the identity function onto the front of the global  
variable, and then reads
it back as an int, and tries to do addition on it.

Cheers,
Bernie.


More information about the Haskell-Cafe mailing list