在可变矢量上使用par monad(parMapM)

时间:2015-09-19 14:50:09

标签: haskell vector monads ghc mutable

我已经尝试了几个小时,但似乎无法将其编译。我正在尝试与可变向量并行执行简单操作,但是我遇到了编译错误。

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

a = V.fromList [1,2,3,4,5,6]

b = do
    c <- V.unsafeThaw a
    runPar $ parMapM
        (liftM (\i -> M.write c i 100))
        [0..5]
    return $ V.unsafeFreeze c

在“c&lt; - V.unsafeThaw a”行上我收到编译错误

 Couldn't match type `primitive-0.5.2.1:Control.Monad.Primitive.PrimState     []'
                 with `primitive-0.5.2.1:Control.Monad.Primitive.PrimState m0'
   NB: `primitive-0.5.2.1:Control.Monad.Primitive.PrimState' is a type function, and may not be injective
   The type variable `m0' is ambiguous
   Expected type: [M.MVector
                     (primitive-0.5.2.1:Control.Monad.Primitive.PrimState m0) Integer]
     Actual type: [M.MVector
                     (primitive-0.5.2.1:Control.Monad.Primitive.PrimState []) Integer]
   In a stmt of a 'do' block: c <- V.unsafeThaw a
   In the expression:
     do { c <- V.unsafeThaw a;
          runPar $ parMapM (liftM (\ i -> M.write c i 100)) [0 .. 5];
          return $ V.unsafeFreeze c }

在“return $ V.unsafeFreeze c”行中我收到错误

   Couldn't match type `primitive-0.5.2.1:Control.Monad.Primitive.PrimState m1'
                 with `primitive-0.5.2.1:Control.Monad.Primitive.PrimState m0'
   NB: `primitive-0.5.2.1:Control.Monad.Primitive.PrimState' is a type function, and may not be injective
   The type variables `m0', `m1' are ambiguous
   Expected type: M.MVector
                    (primitive-0.5.2.1:Control.Monad.Primitive.PrimState m1) Integer
     Actual type: M.MVector
                    (primitive-0.5.2.1:Control.Monad.Primitive.PrimState m0) Integer
   Relevant bindings include
     c :: M.MVector
            (primitive-0.5.2.1:Control.Monad.Primitive.PrimState m0) Integer
       (bound at C:\Users\Administrator\workspace\test\src\Main.hs:11:5)
     b :: [m1 (V.Vector Integer)]
       (bound at C:\Users\Administrator\workspace\test\src\Main.hs:10:1)
   In the first argument of `V.unsafeFreeze', namely `c'
   In the second argument of `($)', namely `V.unsafeFreeze c'

你能帮我找出我做错的事吗?

1 个答案:

答案 0 :(得分:1)

试试这个:

import qualified Data.Vector as V
import qualified Data.Vector.Mutable as M
import Control.Monad.Par as Par
import Control.Monad
import Control.Monad.Par.IO as ParIO
import Control.Monad.Trans (liftIO)

a = V.fromList [1,2,3,4,5,6]

foo = do
  mv <- V.unsafeThaw a
  ParIO.runParIO $ parMapM (\i -> liftIO $ M.write mv i 100) [0..5]
  V.unsafeFreeze mv

请注意,您只能在IO或ST monad中执行M.write。 IO当然更容易处理。