【问题标题】:How do I write a Data.Vector.Unboxed instance in Haskell?如何在 Haskell 中编写 Data.Vector.Unboxed 实例?
【发布时间】:2012-06-02 23:22:07
【问题描述】:

我有一个数值应用程序,它对概率的负对数做了很多工作,它(因为概率范围从零到一)取正双精度值或负无穷大(如果基础概率为零) .

我将这些与新类型 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

现在,在 Viterbi 算法的实现中,我一直在使用 Data.Vector 很多,实际上我有一些 Data.Vectors 和 Scores。在尝试进行一些性能调整时,我决定尝试使用Data.Vector.Unboxed。但是,我需要为Unbox 编写一个实例,该实例无法派生,而且我无法完全弄清楚我需要做什么(特别是Unbox 类型类的合同是什么)。因为Score 真的是一个Double 有一些有用的构造函数和语义,这应该是可能的,我想。据我所知,我需要能够告诉Data.Vector.UnboxedScores 向量中的每个插槽必须有多大,我猜如何读写它们(但见鬼,它们很多比如Doubles)。

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

【问题讨论】:

    标签: haskell typeclass unboxing


    【解决方案1】:

    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)
    

    【讨论】:

    • 这在 ghc 7.8.4 中不再有效,提供Could not coerce from ‘Data.Vector.Primitive.Vector Double’ to ‘U.Vector Score’ because ‘Data.Vector.Primitive.Vector Double’ and ‘U.Vector Score’ are different types. arising from the coercion of the method ‘Data.Vector.Generic.Base.basicLength’ from type ‘U.Vector Double -> Int’ to type ‘U.Vector Score -> Int’ Possible fix: use a standalone 'deriving instance' declaration, so you can specify the instance context yourself When deriving the instance for (Vector U.Vector Score)
    • ghc.haskell.org/trac/ghc/ticket/9112 似乎相关,但我没有看到他们提到解决方案。
    • 正如 unhammer 指出的那样,自 GHC-7.8 以来,此解决方案不再有效。 Apparently 推荐的方法是使用 vector-th-unbox 直到底层 GHC 问题得到解决。
    猜你喜欢
    • 2018-03-02
    • 1970-01-01
    • 1970-01-01
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多