2010-04-14 73 views
13

我有一個F#記錄類型和希望的領域之一是可選的:F#可選記錄字段

type legComponents = { 
    shares : int<share> ; 
    price : float<dollar/share> ; 
    totalInvestment : float<dollar> ; 
} 

type tradeLeg = { 
    id : int ; 
    tradeId : int ; 
    legActivity : LegActivityType ; 
    actedOn : DateTime ; 
    estimates : legComponents ; 
    ?actuals : legComponents ; 
} 

在tradeLeg型我想實際值字段是可選的。我似乎無法弄清楚,也不能在網上找到可靠的例子。看起來這應該很容易,就像

let ?t : int = None 

但我真的不能似乎得到這個工作。唉 - 謝謝你

牛逼

回答

6

如何Option

type tradeLeg = { 
    id : int option; 
    tradeId : int option; 
    legActivity : LegActivityType option; 
    actedOn : DateTime option; 
    estimates : legComponents option; 
    actuals : legComponents option; 
} 
+0

let me = StrangleMyself!option 我認真考慮過今天下午我試過了。忙於進出會議 - 我想我需要做筆記和閱讀規格做得更好。我虛心地謝謝你 Todd – akaphenom 2010-04-14 01:33:44

0
actuals : legComponents option; 
0

爲現有崗位評論,下面是選項類型的例子:

.. 
id: int option; 
.. 

match id with 
    | Some x -> printfn "the id is %d" x 
    | None -> printfn "id is not available" 

可以盲目ID與期權價值:

let id = Some 10 

let id = None 

並引用此MSDN頁碼:http://msdn.microsoft.com/en-us/library/dd233245%28VS.100%29.aspx

Here是選項類型的另一個示例,您可能會對Seq.unfold感興趣。

22

正如其他人指出的那樣,您可以使用'a option類型。但是,這不會創建可選的記錄字段(其創建時無需指定其值)。例如:

type record = 
    { id : int 
    name : string 
    flag : bool option } 

要創建record類型的值,你仍然需要提供flag字段的值:(據我所知)

let recd1 = { id = 0; name = "one"; flag = None }  
let recd2 = { id = 0; name = "one"; flag = Some(true) } 

// You could workaround this by creating a default record 
// value and cloning it (but that's not very elegant either): 
let defaultRecd = { id = 0; name = ""; flag = None }  
let recd1 = { defaultRecd with id = 0; name = "" } 

不幸的是,你可以」 t創建一個記錄,該記錄具有一個可以在創建時省略的真正選項字段。但是,你可以使用一個類型與構造函數,然後你可以使用?fld語法創建構造函數的可選參數:

type Record(id : int, name : string, ?flag : bool) = 
    member x.ID = id 
    member x.Name = name 
    member x.Flag = flag 

let rcd1 = Record(0, "foo") 
let rcd2 = Record(0, "foo", true) 

類型的rcd1.Flagbool option,您可以使用模式匹配使用它(如尹竺所示)。記錄和簡單類之間唯一顯着的區別就是,不能使用with語法來克隆類,並且類不會(自動)實現結構比較語義。

+0

Got it!thx: type record = {i:int flag:bool option} let recd1 = {i = 0; flag = None} let recd2 = {i = 0; flag = Some(true)} type record2 = { r1:record; r2:記錄選項 } let recd3 = { r1 = {i = 0; flag = None}; r2 = Some({i = 0; flag = Some(true)})} let recd4 = { r1 = {i = 0; flag = None}; r2 =無} – akaphenom 2010-04-14 02:01:12

+0

@akaphenom:註釋中的代碼不具有特別的可讀性。但我想你的例子使用類可能看起來像這樣:let recd4 = Record2(Record(0))'(沒有設置'r2'和'flag')或者例如'recd5 = Record2(Record(0,true) ,Record(1,false))'設置所有屬性時。 – 2010-04-14 02:23:19