简体   繁体   中英

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

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_ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM