4

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.

2 Answers 2

5

The GM.MVector v a 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
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

The close correspondence with my code helped me improve my type declaration skills.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.