[Haskell-cafe] Monad Imparative Usage Example

Donald Bruce Stewart dons at cse.unsw.edu.au
Wed Aug 2 06:50:26 EDT 2006


kaveh.shahbazian:
> Monad Imparative Usage Example
> 
> Thanks for your replies. I have not haskell on this computer and I
> will try this solutions tonight.
> I must notice that IO computations is not the point here. My target is
> to have this code for mutable variable 'var'.

Still not entirely clear what your goal in the translation is.
The most "Haskell" way would be to emulate a mutable variable with a state
monad, but you seem to want an actual named mutable variable?

So here's an example, like Seb's, where we create a mutable variable (in
the IO monad) and mutate it all over the place. This uses similar
scoping to your original code. For fun we use MVars instead of IORefs.

    import Control.Concurrent.MVar
      
    main = do
        var <- newEmptyMVar
        let write = withMVar var print
        
            f1 = do putMVar var 0
                    write

            f2 = do modifyMVar_ var (return.(+4))
                    write
        f1
        f2
        swapMVar var 10
        write

Produces:
    $ runhaskell A.hs
    0
    4
    10

Of course, if you're learning Haskell, you should probably try to
/avoid/ mutable variables for a while.

-- Don


More information about the Haskell-Cafe mailing list