在F#API中,有类似Option.ofNull的东西吗?

时间:2014-06-25 21:22:34

标签: f#

我从F#中使用的许多API都允许空值。我喜欢把它们变成选项。有一个简单的内置方法来做到这一点?这是我这样做的一种方式:

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

然后我可以这样使用Option.ofNull

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

是否有内置功能可以做到这一点?

根据Daniel的回答,不需要equality。可以使用null约束。

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

1 个答案:

答案 0 :(得分:5)

没有任何内置功能可以做到这一点。顺便说一下,你可以不用等式约束:

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

或者,如果您想处理从其他语言和Unchecked.defaultof<_>传递的F#值:

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