-
Couldn't load subscription status.
- Fork 60
Description
the indexArrayM docs read:
-- | Monadically read a value from the immutable array at the given index.
-- This allows us to be strict in the array while remaining lazy in the read
-- element which is very useful for collective operations. Suppose we want to
-- copy an array. We could do something like this:
--
-- > copy marr arr ... = do ...
-- > writeArray marr i (indexArray arr i) ...
-- > ...
--
-- But since primitive arrays are lazy, the calls to 'indexArray' will not be
-- evaluated. Rather, @marr@ will be filled with thunks each of which would
-- retain a reference to @arr@. This is definitely not what we want!
--
-- With 'indexArrayM', we can instead write
--
-- > copy marr arr ... = do ...
-- > x <- indexArrayM arr i
-- > writeArray marr i x
-- > ...
--
-- Now, indexing is executed immediately although the returned element is
-- still not evaluated.
--Something about this function, which I feel should be mentioned in the docs, is that one should usually (as i imagine, at least) wish to be strict in indexing into an array. Consider a situation in which one indexes into an array strictly, and no references to the array exist. Then, when GC occurs, the array will be GC'd. However, if the indexing is lazy, the indexing could potentially not have occured yet, and even if no references to the array exist, the array will not be GC'd. In most cases i think users would prefer indexArray## for this reason. The only Monads for which this isn't really a problem are those strict in the left argument of bind (e.g. IO, ST), since binding the result of indexArrayM to a computation therein will actually force the indexing to happen.
Another reason lazy indexing into an array might be undesirable is that indexing is so cheap for everything in this library, i can't see laziness being beneficial in most situations involving primitive. If people agree that this should be mentioned in the docs, I would like to put up a PR.