2012-06-02 62 views
17

我有一個數字應用程序,做很多與負概率的日誌,哪些(因爲概率範圍從零到一)採取積極的雙打或負無窮(如果基礎概率爲零)的值的工作。如何在Haskell中編寫Data.Vector.Unboxed實例?

我使用這些具有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 

現在,在Viterbi算法的實現,我一直在使用Data.Vector了很多,我確實有一些Data.Vector小號Score s。在嘗試進行一些性能調整時,我決定嘗試使用Data.Vector.Unboxed。但是,我需要編寫一個Unbox的實例,這個實例不能派生出來,我不能完全弄清楚我需要做什麼(特別是類型類型Unbox的合同是什麼)。由於Score真的是一個Double與一些有用的構造函數和語義,這應該是可能的,我想。據我所知,我需要能夠告訴Data.Vector.Unboxed每個插槽在Score的矢量中必須有多大,我猜如何讀取和寫入它們(但是,他們很像Double s) 。

那麼,我該怎麼辦?謝謝!

回答

15

Unbox type class沒有任何方法 - 它只是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) 
+0

太棒了,謝謝! –

+2

這不再適用於ghc 7.8.4,因爲'Data.Vector.Primitive.Vector Double'和'U.Vector'給出'不能從'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)派生實例時,' – unhammer

+1

https://ghc.haskell.org/trac/ghc/ticket/9112似乎是相關的,儘管我沒有看到他們提到了一個解決方案。 – unhammer