Many APIs that I consume from F# allow null values. I like turning them into Options. Is there a simple built-in way to do this? Here is one way I have done so:
type Option<'A> with
static member ofNull (t:'T when 'T : equality) =
if t = null then None else Some t
Then I'm able to use Option.ofNull
like so:
type XElement with
member x.El n = x.Element (XName.Get n) |> Option.ofNull
Is there something built-in that already does this?
Based on Daniel's answer, equality
isn't needed. null
constraint can be used instead.
type Option<'A> with
static member ofNull (t:'T when 'T : null) =
if t = null then None else Some t