我有一个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
但我似乎无法让这个工作。呃 - 谢谢你
Ť
答案 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感兴趣。