Tobias Hermann
Tobias Hermann

Reputation: 10956

Apply a list of changes to elements of a mutable Vector

Given is a List of changes I want to apply to the elements of a Vector. How can this be achieved with Mutation? My current code looks like this so far:

import Control.Monad.ST
import qualified Data.Vector.Mutable as M
import qualified Data.Vector as V

main :: IO ()
main = do
    let v = V.fromList [8,7,4,1,5] :: V.Vector Integer
    -- The elements in changes are pairs of vector index and change to apply.
    let changes = [(0, (+1)), (3, (*3)), (2, (/2))]
    let v' = applyChanges changes v
    print $ V.toList v'

applyChanges changes v = runST $ do
    mV <- V.thaw v
    -- apply (+1) to element 0 -> [9,7,4,1,5]
    -- apply (*3) to element 3 -> [9,7,4,3,5]
    -- apply (/2) to element 2 -> [9,7,2,3,5]
    V.freeze mV

Upvotes: 0

Views: 81

Answers (1)

bheklilr
bheklilr

Reputation: 54078

Using mapM_, you could do

apply mvec (idx, f) = do
    val <- M.read mvec idx
    M.write mvec idx $ f val

applyChanges :: [(Int, Integer -> Integer)] -> V.Vector Integer -> V.Vector Integer
applyChanges changes vec = runST $ do
    mV <- V.thaw v
    mapM_ (apply mV) changes
    V.freeze mV

main = do
    let v = V.fromList [8,7,4,1,5] :: V.Vector Integer
    let changes = [(0, (+1)), (3, (*3)), (2, (/2))]
    print $ V.toList $ applyChanges changes v

All I've really done is written a function that takes a vector and a single change to apply, then mapped that over all the changes in your list. The necessary steps were M.read, M.write, and mapM_.

Upvotes: 4

Related Questions