gpt4 book ai didi

f# - 在 F# API 中,是否有类似 Option.ofNull 的东西?

转载 作者:行者123 更新时间:2023-12-05 01:03:39 24 4
gpt4 key购买 nike

我从 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

是否有内置的东西已经做到了这一点?

基于丹尼尔的回答, equality不需要。 null可以使用约束代替。
type Option<'A> with
static member ofNull (t:'T when 'T : null) =
if t = null then None else Some t

最佳答案

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

//'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

关于f# - 在 F# API 中,是否有类似 Option.ofNull 的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24418816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com