4

I just posted this code:

import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Algorithms.Intro as VAlgo

argSort :: (Ord a, VU.Unbox a) => VU.Vector a -> VU.Vector Int
argSort xs = VU.map fst $ VU.create $ do
    xsi <- VU.unsafeThaw $ VU.indexed xs
    VAlgo.sortBy (comparing snd) xsi
    return xsi

My reasoning was that unsafeThaw is safe to use here because I only thaw the indexed version of xs. However, then it occured to me that unboxed vectors of tuples – like these index-value pairs here – are really stored as two unboxed vectors, one for the indices and one for the values. Hence it seems plausible that indexed would not actually generate a new value vector at all, but just couple it with an index vector. In this case, ST-modifying xsi could possibly mess up xs.

Upon testing, this does not seem to happen though. Can I rely on this, or should I better use thaw?

Community
  • 1
  • 1
leftaroundabout
  • 117,950
  • 5
  • 174
  • 319
  • 1
    Seems like an implementation accident to me. I wouldn't rely on it. – Carl Nov 13 '16 at 20:24
  • 3
    This seems worthy of discussion for vector devs. At least "The immutable vector may not be used after this operation" does not seem to be well-defined or sufficient documentation, and I could easily see myself accidentally using an unsafeThaw in this situation without thinking about it. – jberryman Nov 14 '16 at 01:11
  • A quick glance at [the source code](https://github.com/haskell/vector/blob/master/Data/Vector/Unboxed.hs#L812-L814) reveals that `indexed` is just an alias for [the overloaded version of the same](https://github.com/haskell/vector/blob/master/Data/Vector/Generic.hs#L1000-L1002), which works by converting the input vector to and from a stream. So `indexed`, as implemented, will always return a new vector, rather than a view over the old one. I guess the `Vector` devs decided fusion was more important than sharing in this case. I wouldn't necessarily want to rely on this behaviour though. – Benjamin Hodgson Nov 14 '16 at 12:25

0 Answers0