safe array freezing?

John Meacham john at repetae.net
Tue Dec 30 17:46:49 EST 2003


so, A common idiom when using Control.Monad.ST is to do some
complicated, state using computation to compute a big array which is
then used purely functionally as a read-only array in the rest of the
program. 

to avoid the cost of copying the array at the end, we are forced to use
'unsafeFreeze'. it occurs to me that this particular idiom can actually
be done safely, by adding the following...

runSTArray :: (forall s . (ST s (STArray s i e))) -> Array i e
runSTUArray :: (forall s . (ST s (STUArray s i e))) -> UArray i e

now, since these discard 's' and hence the ability to modify the arrays
they return, they may safely use the final arrays directly as if they
were immutable. 

the routines are also very easy to implement:
runSTArray st = runST $ st >>= unsafeFreeze
runSTUArray st = runST $ st >>= unsafeFreeze          


so, is my logic correct? that runSTArray and runSTUArray need not be
considered unsafe? if so, perhaps we should add these (or some better
generalization that someone comes up with) to the standard libraries, as
it would be nice to be able to use this idiom without resorting to
trickery. (well, user visible trickery at least)
        John

-- 
---------------------------------------------------------------------------
John Meacham - California Institute of Technology, Alum. - john at foo.net
---------------------------------------------------------------------------


More information about the Haskell mailing list