[Haskell-cafe] Is unsafePerformIO safe here?

Luke Palmer lrpalmer at gmail.com
Sun Dec 7 21:28:04 EST 2008

2008/12/7 John Ky <newhoggy at gmail.com>

> Does that mean there is no place to store state while running the
> interpreter and that I have to put the state elsewhere such as a file?  I
> was hoping to avoid that as I'm only prototyping at this stage and don't
> want to write a persistent layer just yet.

Bob is right, that technically it is unsafe.  However, in GHC (I can't speak
for the others) you can make it safe by forcing it not to inline.  Then,
IIRC, you are guaranteed (only in GHC, not in Haskell) that it will be only
created once:

moo :: TVar Int
{-# NOINLINE moo #-}
moo = unsafePerformIO $ newTVarIO 1

Correct, you cannot have global state in safe Haskell.  Make of that what
you will, YMMV, personally I like it (it has positive implications in terms
of semantics and reasoning).  You have to put state elsewhere, but "such as
a file" is a little extreme.  Make it at the GHCi prompt (if there is more
than a teeny bit of initialization, I usually define a helper function to
make this as easy as possible). Then pass it around or put your computation
in a ReaderT (same thing).  You're going to be passing it around when you
write your real application anyway, right?

Also, as your application matures, you know your persistence layer is
probably already done for you in Data.Binary :-)


> Thanks
> -John
> On Mon, Dec 8, 2008 at 11:51 AM, Thomas Davie <tom.davie at gmail.com> wrote:
>> 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
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20081207/2efdd175/attachment.htm

More information about the Haskell-Cafe mailing list