I have a F# record type and want one of the fields to be optional:
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 ;
}
in the tradeLeg type I would like the the actuals field to be optional. I can't seem to figure it out nor can I seem to find a reliable example on the web. It seem like this should be easy like
let ?t : int = None
but I realy can't seem to get this to work. Ugh - thank you
T
How about
Option
?as a comment to the existing posts, here's an example for option type:
you can blind id with a option value:
or
and refer this MSDN page: http://msdn.microsoft.com/en-us/library/dd233245%28VS.100%29.aspx.
Here's another example for option type, and you probably will be interested with Seq.unfold.
As others pointed out, you can use the
'a option
type. However, this doesn't create an optional record field (whose value you don't need to specify when creating it). For example:To create a value of the
record
type, you still need to provide the value of theflag
field:Unfortunately, (as far as I know) you can't create a record that would have a truly option field that you could omit when creating it. However, you can use a class type with a constructor and then you can use the
?fld
syntax to create optional parameters of the constructor:The type of
rcd1.Flag
will bebool option
and you can work with it using pattern matching (as demonstrated by Yin Zhu). The only notable difference between records and simple classes like this one is that you can't use thewith
syntax for cloning classes and that classes don't (automatically) implement the structural comparison semantics.