Generalize runSTArray and runSTUArray

Zemyla zemyla at gmail.com
Wed Aug 21 18:24:58 UTC 2019


The "runSTArray" and "runSTUArray" functions allow efficiently working with
Arrays in the ST monad before turning them immutable; however, they don't
allow any way to return supplemental or alternative information with the
array. There are many times when I've wanted to get an (Array i e, w) or a
Maybe (UArray i e), but I couldn't, and had to use the far-more-inefficient
freezeArray and hope it inlined properly.

What I want are functions that generalize the return types given:

runSTArrayTrav :: Traversable t => (forall s. ST s (t (STArray s i e))) ->
t (Array i e)
runSTArrayTrav m = runST $ m >>= traverse unsafeFreezeSTArray

runSTUArrayTrav :: Traversable t => (forall s. ST s (t (STUArray s i e)))
-> t (UArray i e)
runSTUArrayTrav m = runST $ m >>= traverse unsafeFreezeSTUArray

And then an even more generalized version, which takes a sort of Lens-like
iterator, and allows returning multiple arrays of different kinds, types,
and indices:

runSTArrayWith :: (forall f s. Applicative f => (forall i e. STArray s i e
-> f (Array i e)) -> (forall i e. STUArray s i e -> f (UArray i e)) -> u s
-> f v) -> (forall s. ST s (u s)) -> v
runSTArrayWith tr m = runST $ m >>= tr unsafeFreezeSTArray
unsafeFreezeSTUArray

The advantage of the runSTArrayTrav/runSTUArrayTrav functions, if they're
subsets of the runSTArrayWith function, is that it works with standard
things like (,) and Either, and doesn't require wrapping it in a newtype so
that the s is at the end.

The names of the functions are up for debate, and I know there will be one,
because naming things is one of the two hard problems in computer science,
along with cache invalidation and off-by-one errors.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/libraries/attachments/20190821/e18ab190/attachment.html>


More information about the Libraries mailing list