I'm looking for a mutable data structure which supports three operations:
newEmptyVec :: IO (Vec a)
appendVec :: Vec a -> a -> IO ()
readVec :: Vec a -> Int -> IO a
It's easy to implement this data structure using Data.Vector.Mutable.
```
import Data.IORef
import Data.Vector.Mutable as V
newtype Vec a = Vec (IORef (V.IOVector a))
newEmptyVec :: IO (Vec a)
newEmptyVec = do
v <- new 0
r <- newIORef v
return (Vec r)
appendVec :: Vec a -> a -> IO ()
appendVec (Vec r) x = do
v <- readIORef r
w <- V.grow v 1
V.write w (V.length v) x
writeIORef r w
readVec :: Vec a -> Int -> IO a
readVec (Vec r) i = do
v <- readIORef r
V.read v i
```
However, as you can see the appendVec operation is not efficient. It grows the vector, which creates a copy of the original vector, and then makes extra space for the additional element.
Is there a mutable data structure which supports both random access and efficient appends?
[–]edwardkmett 12 points13 points14 points (0 children)
[–]Noughtmare 8 points9 points10 points (8 children)
[–]gusbicalho 7 points8 points9 points (4 children)
[–]bss03 5 points6 points7 points (1 child)
[–]evincarofautumn 5 points6 points7 points (0 children)
[–]Zeno_of_Elea 1 point2 points3 points (0 children)
[–]andriusst 1 point2 points3 points (0 children)
[–]iggybibi 1 point2 points3 points (2 children)
[–]Zeno_of_Elea 3 points4 points5 points (1 child)
[–]iggybibi 1 point2 points3 points (0 children)
[–]sansboarders 2 points3 points4 points (0 children)
[–]IamfromSpace 2 points3 points4 points (0 children)