2010-04-14 71 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