gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:01:28 27 4
gpt4 key购买 nike

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

{-# 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com