Global variables?

Jon Cast jcast@ou.edu
Fri, 31 Jan 2003 13:41:06 -0600


Glynn Clements <glynn.clements@virgin.net> wrote:

> Pavel G. Zhbanov wrote:

> > Is it even possible to make a "global variable" in Haskell?  If yes,
> > how?

> The usual fudge is:

> 	import IORef
> 	import IOExts

> 	globalVar :: IORef Int
> 	globalVar = unsafePerformIO $ newIORef 0

> However, beware of creating more than one "global variable" of the
> same type. If you enable optimisation, common subexpression
> elimination may result in both names referring to the same IORef.

Is this true?  It seems wrong---I don't think expressions involving
unsafePerformIO should be combined, for precisely this reason.

Even if it is true, though, the following kludge should work:

> {-# NOINLINE mkGlobalVar #-}
> mkGlobalVar :: String -> alpha -> IORef alpha
> mkGlobalVar name value = usafePerformIO (newIORef value)

> globalVar = mkGlobalVar "globalVar" 0

This ensures that no common sub-expression elimination will be
performed.

> -- 
> Glynn Clements <glynn.clements@virgin.net>

Jon Cast