Haskell:从向量到未装箱的向量

时间:2019-03-06 21:48:37

标签: haskell vector

今天,当我突然意识到缺少实例时,我正在将一些使用Data.Vector的代码转换为“内存效率更高”的Data.Vector.Unboxed

如果我在ghci中这样做:

import qualified Data.Vector as V
V.singleton V.empty :: V.Vector (V.Vector Int)
[[]]

那是正确的,Vector打印正确。但是,如果我尝试使用Vector.Unboxed

import qualified Data.Vector.Unboxed as VU
:set -XFlexibleContexts
VU.singleton VU.empty :: VU.Vector (VU.Vector Int)

我得到了错误:

<interactive>:10:1: error:
    • No instance for (VU.Unbox (VU.Vector Int))
        arising from a use of ‘VU.singleton’
    • In the expression:
          VU.singleton VU.empty :: VU.Vector (VU.Vector Int)
      In an equation for ‘it’:
          it = VU.singleton VU.empty :: VU.Vector (VU.Vector Int)

哪个让我想到了一个问题,如何正确实现向量的无框向量?



旁注:

我要达到的目标是一个通用的splitChunks函数,其基本前提是将向量拆分为固定大小的子向量,使用公共向量的非常原始的实现如下:

-- With an arbitrary vector and a positive integer of known size it will create a vector that has splitted the original into sections. Example:
-- vec = [1,2,3,4,5,6,7,8,9,10]
-- size = 4
-- result = [[1,2,3,4],[5,6,7,8],[9,10]]
splitChunks :: V.Vector p -> Int -> V.Vector (V.Vector p)
splitChunks vec size
    | size <= 0 = V.empty
    | otherwise = fst $ until condition opr (V.empty, vec)
    where condition = V.null . snd
          opr (x, y) = let (l, r) = V.splitAt size y in (V.snoc x l, r)

然后,当我尝试从Vector移到Vector.Unboxed时,遇到了与上述相同的问题。

0 个答案:

没有答案