[Haskell-cafe] global variables

Donald Bruce Stewart dons at cse.unsw.edu.au
Thu May 17 22:30:04 EDT 2007


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

As other posters have said, you'll need to state what you're trying to
do. For one particular case, that of a program that needs access to
state over its lifetime, State monads are used. Here's a small example:

    -- import global variable support
    import Control.Monad.State

    -- declare our global variables. here we just have a single Int
    type Global = Int

    -- initialise them on startup
    main = print (evalState main' 7) -- 7 is the default value

    -- code that runs with access to these globals, note that its type
    -- indicates that it uses globals:

    main' :: State Global Int
    main' = do
        i <- get            -- get and modify the global a few times
        put (i ^ 2)
        modify $ \i -> i `div` 2
        i <- get
        return i

We can run this:

    $ runhaskell A.hs
    24

-- Don


More information about the Haskell-Cafe mailing list