[Haskell-cafe] Monad Imparative Usage Example
Donald Bruce Stewart
dons at cse.unsw.edu.au
Wed Aug 2 06:50:26 EDT 2006
> 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.
main = do
var <- newEmptyMVar
let write = withMVar var print
f1 = do putMVar var 0
f2 = do modifyMVar_ var (return.(+4))
swapMVar var 10
$ runhaskell A.hs
Of course, if you're learning Haskell, you should probably try to
/avoid/ mutable variables for a while.
More information about the Haskell-Cafe