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

标签 haskell typeclass unboxing

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

我将这些与新类型 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.VectorScore s。在尝试进行一些性能调整时,我决定尝试使用 Data.Vector.Unboxed .但是,我需要为 Unbox 编写一个实例,它无法派生,我也不太清楚我需要做什么(特别是 Unbox 类型类的契约(Contract)是什么)。由于Score真的是Double我想,有了一些有用的构造函数和语义,这应该是可能的。据我所知,我需要能够告诉Data.Vector.Unboxed Score 的向量中的每个槽有多大s 必须是,我猜如何读写它们(但见鬼,它们很像 Double s)。

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

最佳答案

Unbox type 类没有任何方法——它只是 Vector 的简写。和 MVector类型类。推导出这些,以及 Unbox类(class)是免费的(通过派生或只是在某处自己的行上写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)

关于haskell - 如何在 Haskell 中编写 Data.Vector.Unboxed 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10866676/

相关文章:

c++ - haskell 中用多态性替换条件的等效模式是什么?

haskell - 如何指定类型类实例?

c# - 比较盒装值类型

java - 拆箱问题

haskell - 操作类型构造函数的参数顺序

Haskell,将泛型与 Char 进行比较

scala - 实现某个类型类的类列表

java - 从 Integer 包装类转换为 int 原始类

Haskell 和纯函数结果的内存

haskell - 无法将类类型与 haskell 中的特定类型匹配