haskell - 简单数据类型的未装箱向量

标签 haskell vector unboxing

我想在简单的新类型上使用未装箱的向量,但我不清楚如何启用它。到目前为止我所拥有的:

{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}

module UnboxedTest where

import Data.Vector.Unboxed
import Data.Word

newtype X = X Word64 deriving (Unbox)

我得到:

src/UnboxedTest.hs:11:32: error:
    • No instance for (Data.Vector.Generic.Base.Vector Vector X)
        arising from the 'deriving' clause of a data type declaration
      Possible fix:
        use a standalone 'deriving instance' declaration,
          so you can specify the instance context yourself
    • When deriving the instance for (Unbox X)
   |
11 | newtype X = X Word64 deriving (Unbox)

如何将其放入未装箱的向量中?

最佳答案

如果有一个同构类型已经可以存储在未装箱的向量中,那就非常简单了。对于Point,即(Word64, Word64)

您必须按照该文档页面的说明进行操作并编写:

{-# LANGUAGE TypeFamilies #-}
import Data.Vector.Unboxed
import Data.Vector.Unboxed.Mutable (MVector)
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Generic.Mutable as GM
import Data.Word

data Point = Point Word64 Word64

newtype instance MVector s Point = MV_Point (MVector s (Word64,Word64))
newtype instance Vector    Point = V_Point  (Vector    (Word64,Word64))

instance GM.MVector MVector Point where
  {-# INLINE basicLength #-}
  basicLength (MV_Point v) = GM.basicLength v
  {-# INLINE basicUnsafeWrite #-}
  basicUnsafeWrite (MV_Point v) i (Point x y) = GM.basicUnsafeWrite v i (x, y)
  ...

instance G.Vector Vector Point where
  {-# INLINE basicLength #-}
  basicLength (V_Point v) = G.basicLength v
  {-# INLINE basicUnsafeIndexM #-}
  basicUnsafeIndexM (V_Point v) i = do
    (x, y) <- G.basicUnsafeIndexM v i
    pure (Point x y)
  ...

instance Unbox Point

这些声明指定如何将您的Point转换为(Word64, Word64)以存储在未装箱的向量中。如果您查看例如 basicUnsafeWritebasicUnsafeIndexM 函数,您会发现实际上确实需要编写一些代码来将 Point 转换为 (Word64, Word64) 并返回。

关于haskell - 简单数据类型的未装箱向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74294618/

相关文章:

c++ - 如何将char vector 转换为stringstream

arrays - Scala 数组与向量

c# - 拆箱到更大的值类型

java - 通过传入单个元素原始数组来避免装箱

haskell - 仅在 pretty-print 时坚持使用 2 种布局

haskell - 改变 Haskell 中记录的值

vector - 用任何类型的元组定义向量

java - 通过自动/拆箱操作泛型

haskell - 我如何在 Traveler 实现中最好地表达这种关系

haskell - 对 "Learn you a Haskell"上的 State Monad 代码感到困惑