Is there something like Option.ofNull in the F # API?

Many of the APIs I use from F # are nullable. I like to turn them into Options. Is there a simple built-in way to do this? Here is one way I did this:

type Option<'A> with
    static member ofNull (t:'T when 'T : equality) =
        if t = null then None else Some t

Then I can use Option.ofNullas follows:

type XElement with
    member x.El n = x.Element (XName.Get n) |> Option.ofNull

Is there something inline that already does this?

Based on Daniel's answer, equalitynot required. Instead, a restriction may be used null.

type Option<'A> with
    static member ofNull (t:'T when 'T : null) =
        if t = null then None else Some t
+4
source share
1 answer

There is nothing built in for this. BTW, you can do without equality restrictions:

//'a -> 'a option when 'a : null
let ofNull = function
    | null -> None
    | x -> Some x

or, if you want to process F # values ​​passed from other languages, and Unchecked.defaultof<_>:

//'a -> 'a option
let ofNull x = 
    match box x with
    | null -> None
    | _ -> Some x
+5

Source: https://habr.com/ru/post/1546056/


All Articles