我从F#中使用的许多API都允许使用空值.我喜欢把它们变成选项.有一个简单的内置方法来做到这一点?这是我这样做的一种方式:
type Option<'A> with
static member ofNull (t:'T when 'T : equality) =
if t = null then None else Some t
Run Code Online (Sandbox Code Playgroud)
然后我就可以这样使用Option.ofNull:
type XElement with
member x.El n = x.Element (XName.Get n) |> Option.ofNull
Run Code Online (Sandbox Code Playgroud)
是否有内置的东西已经这样做了?
根据丹尼尔的回答,equality不需要.null可以使用约束来代替.
type Option<'A> with
static member ofNull (t:'T when 'T : null) =
if t = null then None else Some t
Run Code Online (Sandbox Code Playgroud)
没有内置的东西可以做到这一点.顺便说一句,你可以没有相等约束:
//'a -> 'a option when 'a : null
let ofNull = function
| null -> None
| x -> Some x
Run Code Online (Sandbox Code Playgroud)
或者,如果您想处理从其他语言传递的F#值,并且Unchecked.defaultof<_>:
//'a -> 'a option
let ofNull x =
match box x with
| null -> None
| _ -> Some x
Run Code Online (Sandbox Code Playgroud)