2010-05-08 97 views
0

我想創建一個類,將存儲數據的時間序列 - 按組織組織,但我有一些編譯錯誤,所以我剝離到基礎(只是一個簡單實例化),仍然無法克服編譯錯誤。我希望以前有人可能看到過這個問題。柯樂的定義是:F#類與泛型:'構造函數不推薦'錯誤

type TimeSeriesQueue<'V, 'K when 'K: comparison> = class 
     val private m_daysInCache: int 
     val private m_cache: Map<'K, 'V list ref > ref; 
     val private m_getKey: ('V -> 'K) ; 

     private new(getKey) = { 
      m_cache = ref Map.empty 
      m_daysInCache = 7 ; 
      m_getKey = getKey ; 
     } 

end 

所以這看起來不錯,我(也可能不是,但可是沒有任何錯誤或警告) - 實例化獲得誤差:

type tempRec = { 
    someKey: string ; 
    someVal1: int ; 
    someVal2: int ; 
} 

let keyFunc r:tempRec = r.someKey 
// error occurs on the following line 
let q = new TimeSeriesQueue<tempRec, string> keyFunc 

This construct is deprecated: The use of the type syntax 'int C' and 'C ' is not permitted here. Consider adjusting this type to be written in the form 'C'

注意這可能是簡單的愚蠢 - 我只是從假期回來,我的大腦仍然在時區滯後...

回答

7

編譯器只是說你需要用括號括起來的構造函數的參數:

// the following should work fine 
let q = new TimeSeriesQueue<tempRec, string>(keyFunc) 

還有一些其他的問題,但 - 構造函數必須是公共的(否則就不能稱之爲)和keyFunc參數也應該是在括號(否則,編譯器會認爲類型標註是函數的結果):

let keyFunc (r:tempRec) = r.someKey 

您也可以考慮使用隱式構造函數的語法,這使得類聲明在F#簡單得多。構造函數的參數在類的身體會自動變爲可用,你可以聲明(私人)領域簡單地使用let

type TimeSeriesQueue<'V, 'K when 'K: comparison>(getKey : 'V -> 'K) = 
    let daysInCache = 7 
    let cache = ref Map.empty 

    member x.Foo() =() 
+0

我也注意到與keyFunc錯字 - 必須滿足以下條件,因爲我是簡化了我的代碼帖子。我確實在實例化過程中添加了parens,它只是產生了第二個編譯錯誤: 「Method or object constructor'TimeSeriesQueue'2'not found」 我不反對將類語法改爲隱式 - 但我應該能夠解決它明確以及... – akaphenom 2010-05-08 13:35:24

+0

沒關係...度假rediculousness,構造者被標記爲私人... – akaphenom 2010-05-08 13:37:24