Haskell: how to fix the error with "Add instance declaration for (Unbox A)" when using unpacked vectors?

I wrote code in which a small part of the code takes a large one-dimensional Unboxed.Vector and returns them as a vector (vector a).

Part of the code gives an error. Here is a sample code that looks like the actual code and gives the same error.

import Data.Vector.Unboxed as D xs = [0,1,2,3,4,5,6,7,8,9,10,11] rows = 3 cols = 4 sb = D.fromList xs takeRows::Int -> Int -> Vector Int -> Vector (Vector Int) takeRows rows cols x0 = D.map (\x -> D.slice x (fromIntegral cols) x0) starts where starts = D.enumFromStepN 0 cols rows -- takeRowsList::Int -> Int -> Vector Int -> [Vector Int] -- takeRowsList rows cols x0 = Prelude.map (\x -> D.slice x (fromIntegral cols) x0) starts -- where -- starts = D.toList . D.enumFromStepN 0 cols $ rows 

error

 No instance for (Unbox (Vector Int)) arising from a use of `D.map' Possible fix: add an instance declaration for (Unbox (Vector Int)) In the expression: D.map (\ x -> slice x (fromIntegral cols) x0) starts In an equation for `takeRows': takeRows rows cols x0 = D.map (\ x -> slice x (fromIntegral cols) x0) starts where starts = enumFromStepN 0 cols rows 

I wrote a similar takeRowsList function that makes an external vector like a list, and it does not suffer from the same problem. I also included it above, but commented on this to demonstrate my problem.

I understand that some functions need type definitions when I use them with Unboxed Vectors. But in this case I’m at an impasse where to put the type definition. I tried quite a few types, defining everything, and I keep getting the above error.

Thanks in advance for your help.

+4
source share
2 answers

You cannot have an unboxed vector containing another vector. Only some primitive data types can be unpacked, namely those for which Unbox instances are Unbox . Vectors are not primitive data types.

What you can do is return your function to the normal (boxed) vector of unboxed vectors.

+2
source

Non-free vectors must know the size of their elements, and this size must be constant. Vectors can have different sizes, so they cannot be elements of unrelated vectors. They can be elements of nested vectors, although if the lists are not suitable for what you are doing, you can make it a boxed vector ( import qualified Data.Vector as B and qualify the corresponding functions with B instead of D).

+7
source

Source: https://habr.com/ru/post/1382079/


All Articles