[Haskell-cafe] Beginner: IORef constructor?

Donald Bruce Stewart dons at cse.unsw.edu.au
Fri Dec 1 06:47:46 EST 2006


tjay.dreaming:
> Thanks for the demo. I don't actually understand what's going on yet,
> but your code doesn't  really use a global variable, does it? From
> what I can understand, the main function is passing the State to the
> other functions.

Right, via the monad. The monad does all the threading.

> 
> I think I was careless about mixing "IO functions" and normal
> functions. Now that I think about it, my "global variable" really
> should only be available to IO functions, so the following should be
> just fine:
> 
> ----------------------------------------------------------
> module Global where
> 
> import Data.IORef
> 
> theGlobalVariable = newIORef []
> 
> testIt = do ref <- theGlobalVariable
>            original <- readIORef ref
>            print original
>            writeIORef ref [1,2,3]
>            new <- readIORef ref
>            print new
> ----------------------------------------------------------
> 
> I've got a lot to learn about Haskell...

Now, if you wanted to pass that ref to other functions, you'd have to
thread it explicitly -- unless you store it in a state monad :)

    i.e. do ref <- theGlobalVariable
            ...
            .. f ref
            ...

      f r = do  
            ...
            .. g r
            ...

I kind of jumped ahead that step, and went straight to the implicitly
threaded version. 

-- Don


More information about the Haskell-Cafe mailing list