简体   繁体   中英

Creating a mutable Data.Vector in Haskell

I wish to create a mutable vector using Data.Vector.Generic.Mutable.new. I have found examples that create a mutable vector by thawing a pure vector, but that's not what I wish to do.

Here is one of many failed attempts:

import Control.Monad.Primitive
import qualified Data.Vector.Generic.Mutable as GM

main = do
  v <- (GM.new 10) :: (GM.MVector v a) => IO (v RealWorld a)
  GM.write v 0 (3::Int)
  x <- GM.read v 0
  putStrLn $ show x

giving me the error

No instance for (GM.MVector v0 Int)
  arising from an expression type signature
Possible fix: add an instance declaration for (GM.MVector v0 Int)

I tried variations based on the Haskell Vector tutorial with no luck.

I would also welcome suggestion on cleaner ways to construct the vector. The reference to RealWorld seems ugly to me.

The GM.MVector va constaint is ambigous in v . In other words, from the type information you've given GHC, it still can't figure out what specific instance of GM.MVector you want it to use. For a mutable vector of Int use Data.Vector.Unboxed.Mutable .

import qualified Data.Vector.Unboxed.Mutable as M

main = do
    v <- M.new 10
    M.write v 0 (3 :: Int)
    x <- M.read v 0
    print x

I think the problem is that you have to give v a concrete type -- like this:

import Control.Monad.Primitive
import qualified Data.Vector.Mutable as V
import qualified Data.Vector.Generic.Mutable as GM

main = do
  v <- GM.new 10 :: IO (V.MVector RealWorld Int)
  GM.write v 0 (3::Int)
  x <- GM.read v 0
  putStrLn $ show x

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