F#可选记录字段

时间:2010-04-14 00:53:05

标签: f# record optional

我有一个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类型中的

我希望actuals字段是可选的。我似乎无法弄明白,也无法在网上找到可靠的例子。看起来这应该很容易

let ?t : int = None

但我似乎无法让这个工作。呃 - 谢谢你

Ť

4 个答案:

答案 0 :(得分: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 = "" }

不幸的是,(据我所知),您无法创建一个具有真正选项字段的记录,您可以在创建它时省略该字段。但是,您可以使用带有构造函数的类类型,然后可以使用?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.Flag的类型将为bool option,您可以使用模式匹配(如Yin Zhu所示)使用它。记录和像这样的简单类之间唯一值得注意的区别是,您不能使用with语法来克隆类,并且该类不会(自动)实现结构比较语义。

答案 1 :(得分:6)

Option怎么样?

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

答案 2 :(得分:0)

actuals : legComponents option;

答案 3 :(得分:0)

作为对现有帖子的评论,以下是选项类型的示例:

..
id: int option;
..

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

你可以使用选项值盲目识别:

let id = Some 10

let id = None

并参考此MSDN页面:http://msdn.microsoft.com/en-us/library/dd233245%28VS.100%29.aspx

Here是选项类型的另一个例子,你可能会对Seq.unfold感兴趣。