将更改列表应用于可变Vector的元素

时间:2014-09-16 14:58:04

标签: haskell vector mutable

给定是我想要应用于Vector元素的更改列表。如何通过Mutation实现这一目标?到目前为止,我当前的代码看起来像这样:

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

1 个答案:

答案 0 :(得分:4)

使用mapM_,您可以

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

我真正做的就是写一个函数,它接受一个向量和一个单独的更改,然后将其映射到列表中的所有更改。必要的步骤是M.readM.writemapM_