Mon Mar 26 12:18:17 CEST 2012

The ST monad

I need some mutable arrays, i.e. Data.Array.ST and have no idea how it
works.  So, here's some Q&A.

 - How to create a mutable array of size 10 with all 0 elements?

   arr <- newArray (1,10) 0

 - How to convert a mutable array to an immutable one?  The ST Array
   lives in the ST monad, so use newArray and operations on the array
   to construct a monadic value ST (STArray).  runSTArray can be used
   to convert this to Array.

That solves construction and final output.

 - How to iterate over the elements of an array?  Probably simplest is
   to use forM_, which is essentially a combination of map (construct
   a list of monadic computations) and sequence (weave a list of
   monadic computations into one computation).  The function `indices'
   caused some confusion as this is only defined for Array, so I use
   the following approach:

     forA a f = do
       (a,b) <- getBounds a
       forM_ [a..b] f

 - Updating array elements: use writeArray.

[1] http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Monad.html#v:forM-95-
[2] http://www.haskell.org/haskellwiki/Arrays