[Haskell-cafe] Is unsafePerformIO safe here?

Thomas Davie tom.davie at gmail.com
Sun Dec 7 19:51:15 EST 2008


On 8 Dec 2008, at 01:28, John Ky wrote:

> Hi,
>
> Is the following safe?
>
> moo :: TVar Int
> moo = unsafePerformIO $ newTVarIO 1
>
> I'm interested in writing a stateful application, and I wanted to  
> start with writing some IO functions that did stuff on some state  
> and then test them over long periods of time in GHCi.
>
> I was worried I might be depending on some guarantees that aren't  
> actually there, like moo being discarded and recreated inbetween  
> invocations of different functions.

Define safe... In this case though, I would guess it's not safe.  The  
compiler is free to call moo zero, one or many times depending on its  
evaluation strategy, and when it's demanded.  It's possible that your  
TVar will get created many times, and different values returned by the  
"constant" moo.

That sounds pretty unsafe to me.

Bob


More information about the Haskell-Cafe mailing list