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:
type record =
{ id : int
name : string
flag : bool option }
To create a value of the record
type, you still need to provide the value of the flag
field:
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 = "" }
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:
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)
The type of rcd1.Flag
will be bool 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 the with
syntax for cloning classes and that classes don't (automatically) implement the structural comparison semantics.