2009-01-20 27 views
3

問題(我在stillbanging在F#度量單位)F#度量單位,具有通用性

我在做內搭「類型」「通用」功能的問題浮動。

以下實體模型類旨在保持在位置上的累積誤差的標籤頁,基於一個因子「C」。編譯器不喜歡我說0 <「一>中的類型的主體(‘意外的類型參數存在於單位的小節字面’)。

///Corrects cumulative error in position based on s and c 
type Corrector(s_init:float<'a>) = 
    let deltaS ds c = sin (ds/c) //incremental error function 

    //mutable values 
    let mutable nominal_s = s_init 
    let mutable error_s = 0.<'a> //<-- COMPILER NO LIKE 

    ///Set new start pos and reset error to zero 
    member sc.Reset(s) = 
     nominal_s <- s 
     error_s <- 0.<'a> //<-- COMPILER NO LIKE 

    ///Pass in new pos and c to corrector, returns corrected s and current error  
    member sc.Next(s:float<'a>, c:float<'a>) = 
     let ds = s - nominal_s //distance since last request 
     nominal_s <- s //update nominal s 
     error_s <- error_s + (deltaS ds c) //calculate cumulative error 
     (nominal_s + error_s, error_s) //pass back tuple 

另一個相關的問題,我相信,仍與 '通用' 功能做。

在下面的代碼,我試圖做的就是將採取任何類型的花車的#seq並將其應用到只接受「香草」漂浮功能的功能。第三行給出了一個「Value Restriction」的錯誤,我看不到任何出路。 (卸下#解決了問題,但我想避免不必編寫同樣的事情列表,seqs,陣列等)的測量

[<Measure>] type km //define a unit of measure 
let someFloatFn x = x + 1.2 //this is a function which takes 'vanilla' floats 
let MapSeqToNonUnitFunction (x:#seq<float<'a>>) = Seq.map (float >> someFloatFn) x 
let testList = [ 1 .. 4 ] |> List.map float |> List.map ((*) 1.0<km>) 
MapSeqToNonUnitFunction testList 

回答

1

您可以先「編譯器不喜歡」改變爲

let mutable error_s : float<'a> = 0.0<_> 

和編譯器似乎喜歡這樣。

至於第二個問題,我沒有看到相同的錯誤你,這

[<Measure>] type km 
//define a unit of measure 
let someFloatFn x = x + 1.2 //this is a function which takes 'vanilla' floats 
let MapSeqToNonUnitFunction (x:seq<float<_>>) = Seq.map (float >> someFloatFn) x 
let testList = [ 1 .. 4 ] |> List.map float |> List.map ((*) 1.0<km>) 
let testList2 = testList :> seq<_> 
let result = MapSeqToNonUnitFunction testList2 
printfn "%A" result 

編譯對我來說(雖然上溯造型到序列< _>是一個有點討厭,我不知道如果有一個簡單的方法來擺脫它)。

除此之外,我認爲約定是名稱單位參數「U」 V,......而不是「一個」,B,...

0

單元不能用作類型參數。這是因爲在編譯期間被編譯器擦除。這個問題是非常相似: F# Units of measure - 'lifting' values to float<something>

+0

我問一個太,我一定是有點慢上攝取!我想這意味着我有兩個選擇 - 要麼我強迫給定的單位,或者我通過我的零值? – Benjol 2009-01-20 11:54:19

+0

我不知道我明白你不能用作類型參數的意思,「因爲這個工程:讓FN(A:浮法<'a>)(B:浮動<'a>)= A * B – Benjol 2009-01-20 12:03:01

相關問題