[Haskell-cafe] Top-level state debate on the wiki

Keean Schupke k.schupke at imperial.ac.uk
Thu Dec 2 04:08:21 EST 2004


Ben Rudiak-Gould wrote:

Just a small comment on the Wiki page... it says

"Several real-life examples of pure haskell code which needs fast global 
variables to either be implemented efficiently or statically guarantee 
their invariants are given in 
http://www.haskell.org//pipermail/haskell/2004-November/014929.html"

The first example is that of randomIO - not implementable in Haskell, 
however the function,
randoms :: RandomGen g => g -> [a], is (and is probably more idomatic 
haskell anyway).

The second example "Unique",  can be implemented:

    getUniqueSupply = do
       a <- newIORef 0
       return (nextUnique a)
       where

       nextUnqiue n = do
          x <- readIORef n
          writeIORef n (x+1)
          return x

Which should be just as fast as the global version, and all you do is 
pass the 'unique' supply
around... you can even generate a lazy list of unqiues which can be used 
outside the IO monad.
Again the "disadvantage" is that you can have multiple unique supplies 
and you could use the "wrong" one... (which is an advantage in my 
opinion, as it increases flexibility and reuse of the code).

The same applies to the AtomHash, it can be implemented just as 
effieciently without globals...
The only difference appears to be the supposed ability of globals 
stopping the programmer using an alternate Hash... but of course there 
is nothing stopping the programmer using the
wrong global at all! (In other words it seems just as easy to access the 
wrong top-level name as to pass the wrong parameter).

Keean.


More information about the Haskell-Cafe mailing list