如何在Haskell中编写Data.Vector.Unboxed实例?

Noa*_*els 17 unboxing haskell typeclass

我有一个数字应用程序,它使用概率的负对数做了很多工作,其中(因为概率范围从0到1)采用正双精度值或负无穷大值(如果潜在概率为零).

我使用newtype Score如下:

newtype Score = Score Double
  deriving (Eq, Ord)
 -- ^ A "score" is the negated logarithm of a probability

negLogZero :: Score -- ^ Stands in for - log 0
negLogZero = Score 10e1024

negLogOne :: Score -- ^ - log 1
negLogOne = Score 0.0

unScore :: Score -> Double
unScore (Score x) = x

instance Show Score where
  show (Score x) = show x
Run Code Online (Sandbox Code Playgroud)

现在,在Viterbi算法的实现,我已经使用Data.Vector了很多,我确实有一些Data.VectorScore秒.在尝试进行一些性能调整时,我决定尝试使用Data.Vector.Unboxed.但是,我需要编写一个Unbox不能派生的实例,而且我无法弄清楚我需要做什么(特别是Unbox类型类的合同是什么).因为Score实际上它是Double一些有用的构造函数和语义,所以这应该是可能的,我想.据我所知,我需要能够分辨Data.Vector.UnboxedScores 的向量中的每个槽有多大,我想如何读取和写入它们(但是,它们很像Doubles).

那么,我该怎么办?谢谢!

Dan*_*ner 15

Unbox类型的类没有任何方法-它只是速记VectorMVector类型类.推导出这些,并且这个Unbox类是免费的(通过派生或只是instance U.Unbox Score在自己的某处写作).

{-# LANGUAGE GeneralizedNewtypeDeriving #-}
import Data.Vector.Generic.Base
import Data.Vector.Generic.Mutable
import qualified Data.Vector.Unboxed as U
newtype Score = Score Double deriving (Vector U.Vector, MVector U.MVector, U.Unbox)
Run Code Online (Sandbox Code Playgroud)

  • 这不再适用于ghc 7.8.4,因为'不能强行从'Data.Vector.Primitive.Vector Double'到'U.Vector Score',因为'Data.Vector.Primitive.Vector Double'和'U.Vector Score '是不同的类型.从类型'U.Vector Double - > Int'强制方法'Data.Vector.Generic.Base.basicLength'到'U.Vector Score - > Int'类型可能的修复:使用一个独立的'派生实例'声明,因此您可以自己指定实例上下文为(Vector U.Vector Score)`派生实例 (3认同)
  • https://ghc.haskell.org/trac/ghc/ticket/9112似乎很相关,但我没有看到他们提到了解决方案. (2认同)