[Haskell-cafe] How to use STArray?

Sebastian Sylvan sebastian.sylvan at gmail.com
Thu Aug 25 12:51:12 EDT 2005


On 8/25/05, Bayley, Alistair <Alistair_Bayley at ldn.invesco.com> wrote:
> Hello all,
> 
> I have a pure function which uses immutable arrays from Data.Array, but it
> spends about 95% of its time doing array updates. The arrays are used in a
> single-threaded manner (no need for the old values after an array update),
> and the arrays are not returned; just one of the elements. So I want to
> convert it to use STArray, to see if there's a performance gain, but it's
> not clear how I should tie everything together. I'm believe I don't want to
> use runSTArray, because I'm not interested in getting an array back from the
> pure function - just one of the elements.

I think you should use runSTArray, return the array inside that
epression, and then take the resulting Array and finding the element
you want.
runSTArray doesn't actually copy the STArray to a regular array, it
just freezes it. So there's really no performance hit to get the
immutable array as a result.

Like so:

compute :: Int -> Int
compute n = runSTArray ( do
   arr <- newArray (-1, 1) n
   return arr
 ) ! 1


/S

-- 
Sebastian Sylvan
+46(0)736-818655
UIN: 44640862


More information about the Haskell-Cafe mailing list