unsafePerformIO and CSE

5 views
Skip to first unread message

Geoffrey Irving

unread,
Jun 13, 2011, 12:46:11 AM6/13/11
to Dylan Simon, duck...@googlegroups.com
I'd like to do something like this:

lastWrite = unsafePerformIO $ newRef 0
lastRead = unsafePerformIO $ newRef 0

to declare two global mutable variables for use in fixpoint iteration.
Am I correct that Haskell is within its rights to merge these into a
single reference? Is there some clean way of telling Haskell not to
do this?

In this case I can avoid the potential problem in a variety of ways
(changing one of the 0's to 1's, using newRef (0,0), etc.), but it'd
be nice to have a safe general solution.

Thanks,
Geoffrey

Dylan Simon

unread,
Jun 13, 2011, 8:54:53 AM6/13/11
to duck...@googlegroups.com
From Geoffrey Irving <irv...@naml.us>, Sun, Jun 12, 2011 at 09:46:11PM -0700:

You are correct. The standard idiom is:

lastWrite :: IORef Int
{-# NOINLINE lastWrite #-}


lastWrite = unsafePerformIO $ newRef 0

It has been suggested (though I haven't seen concrete evidence) that as of 7.0
this is insufficient and you also need:

{-# OPTIONS_GHC -fno-cse #-}

But of course impacts the whole module, and so people sometimes put all their
"globals" into a single module without other code.

There are also people who claim this whole thing is bad and you should find
other ways to pass globals through functions.

Reply all
Reply to author
Forward
0 new messages