【问题标题】:How to nest unboxed vectors?如何嵌套未装箱的向量?
【发布时间】:2017-05-20 06:44:07
【问题描述】:

这可能是一个非常基本的问题,但我已经四处搜索,似乎找不到答案。

我想使用未装箱的向量来表示一个二维列表。使用法线向量很容易做到这一点:

> import qualified Data.Vector as V
> V.fromList [V.fromList [1..5]]
[[1,2,3,4,5]]

但如果我尝试使用未装箱的向量:

> import qualified Data.Vector.Unboxed as U
> U.fromList [U.fromList [1..5]]

我收到以下错误:

• Non type-variable argument
    in the constraint: U.Unbox (U.Vector a)
  (Use FlexibleContexts to permit this)
• When checking the inferred type
    it :: forall a.
          (U.Unbox (U.Vector a), U.Unbox a, Num a, Enum a) =>
          U.Vector (U.Vector a)

我怀疑这与此有关:

> V.fromList [1..5]
[1,2,3,4,5]

> U.fromList [1..5]
[1.0,2.0,3.0,4.0,5.0]

但我似乎无法理解如何避免这种情况。

提前致谢!

【问题讨论】:

  • 您可能想使用V.Vector (U.Vector a)。如果内部向量不是非常小,这仍然可以为您提供未装箱向量的大部分性能优势。或者,如果内部向量总是相同的小尺寸,请使用不可装箱的固定尺寸类型,例如来自linear package

标签: arrays haskell vector


【解决方案1】:

好吧,我们可以按照编译器给出的建议开始:

> :set -XFlexibleContexts

但是:

> U.fromList [U.fromList [1..5]]

<interactive>:10:1: error:
    • No instance for (U.Unbox (U.Vector a0))
        arising from a use of ‘print’

这里的问题是你不能拆箱矢量(即使它是拆箱的数据)。要拆箱数据类型,您需要准确描述字节布局,包括其大小。但是向量没有大小。考虑例如

U.fromList [U.fromList [1..5], U.fromList [1..7]]

即使在 C 中,这也需要"jagged" matrix,通常用指针表示(= 装箱)。

【讨论】:

  • 我想知道是否不可能定义一个Unbox a =&gt; Unbox (U.Vector a) 实例,其向量将基于一个平面值数组和一个内部向量的起始索引数组。这应该为纯操作提供不错的性能。
  • @leftaroundabout 我认为这可能是可能的。我对Unboxed 的实现不够熟悉,无法估计它是否能很好地工作。 (例如,我刚刚意识到 Unbox 类实际上没有字段。)
  • Unbox a 基本上是(G.Vector U.Vector a, GM.MVector U.MVector a) 的同义词。需要的是basicUnsafeSlice 等的定义。正如我所说,Vector interface 似乎可以用扁平区域方法很好地定义。 MVector 是它变得毛茸茸的地方。
猜你喜欢
  • 2013-06-20
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 2021-02-27
  • 1970-01-01
  • 2012-11-04
  • 1970-01-01
相关资源
最近更新 更多