While using mutable vectors for the first time, I discovered that while Data.Vector.Unboxed
has all the higher level functions you'd expected like map
, fold
, etc., the mutable version Data.Vector.Unboxed.Mutable
has none of these. Trying to use the functions from the immutable package on mutable vectors didn't work.
What is the reason why the mutable vector package lacks a lot of these higher level functions?
I don't know what the designers of these types had in mind when implementing the mutable versions, but the problem I see is to do with laziness and the expectation of consistency.
Suppose I create a mutable vector of three ints, map (* 2)
over them, and then modify the original vector. When I look at the output of map, will I see doubles of old values or of new values? The answer is, it depends on which elements I looked at before modifying, and which after. Consider:
main = do
v <- V.replicate 3 1
let doubled = map (* 2) v
putStrLn "First doubled number is: " ++ show (head doubled)
set v 10
putStrLn "Sum of doubled numbers is: " ++ show (sum doubled)
Although we performed our operations in well-defined chunks, the caching of thunks means that the first element of doubled
will be 2, because we had to force it in order to print it before we set the whole vector to 10, but the last two elements of doubled
will be 20, so our sum is 42: neither the sum of double the original vector, nor the sum of double the final vector. We managed to observe an inconsistent state that our system as a whole was never intended to be in, because we treated a mutable vector as if it were an immutable list, by trying to map
over it lazily.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With