[Haskell-cafe] global variables

Adrian Hey ahey at iee.org
Thu May 17 11:30:22 EDT 2007


Eric wrote:
> H|i,
> 
> Does anyone know of a simple and straightforward way to use global 
> variables in Haskell?

I assume what you're looking for is to be able to have IORefs,MVars
Chans etc at the top level. The standard (for want of a better word)
way to do this is known commonly known as the "unsafePerformIO hack".

myTopLevelFlag :: IORef Bool
{-# NOINLINE myTopLevelFlag #-}
myTopLevelFlag = unsafePerformIO (newIORef False)

With ghc you should also compile which make use of the unsafePerformIO
hack using the -fno-cse flag (to inhibit common sub-expression elemination).

Use something like this at the top of the module..
{-# OPTIONS_GHC -fno-cse #-}

BTW, this is the commonly the subject of flame wars on the Haskell
mailing lists because there appear to be many who passionately believe
and assert that so called "global variables" are (at best) unnecessary
and (at worst) are "evil". These people are quite simply wrong and
should be ignored :-)

They are necessary because they are the only way to ensure important
safety properties of many IO APIs.

I ported the old wiki page about this to the new wiki..
   http://www.haskell.org/haskellwiki/Top_level_mutable_state

If you want to see more examples of the use of the unsafePerformIO
hack you need only look at the source code of the current base
package (you'll find a dozen or so uses of this hack to create
top level mutable state).

Regards
--
Adrian Hey



More information about the Haskell-Cafe mailing list