unsafePerformIO and IORefs

Sven Panne Sven.Panne@informatik.uni-muenchen.de
Mon, 18 Nov 2002 20:05:43 +0100


Hal Daume III wrote:
 > You can't. [...]

Well, you can, but only for CAFs. This idiom/hack is used
quite happily throughout GHC, HOpenGL, H/Direct, ...

Slightly modified stuff from GHC's sources:

------------------------------------------------------------
-- global variables in Haskell :-)
------------------------------------------------------------

global :: a -> IORef a
global a = unsafePerformIO (newIORef a)

#define GLOBAL_VAR(name,value,ty) \
name :: IORef (ty) ; \
name = global (value) ; \
{-# NOINLINE name #-}

------------------------------------------------------------
-- examples
------------------------------------------------------------

GLOBAL_VAR(counter, 0, Int)
GLOBAL_VAR(flag, False, Bool)

------------------------------------------------------------

Cheers,
    S.