在与 C# 库交互时,我发现自己需要 C# 的空合并运算符,用于 Nullable
结构体和引用类型。
是否可以在 F# 中使用单个重载运算符内联适当的 if
来对此进行近似处理?案件?
最佳答案
是的,使用在这个 SO 答案“Overload operator in F#”中发现的一些小技巧。
在编译时正确重载 ('a Nullable, 'a) ->'a
的用法或 ('a when 'a:null, 'a) -> 'a
对于单个运算符可以内联。偶('a option, 'a) -> 'a
可以扔进去以获得更大的灵活性。
为了提供更接近 c# 运算符的行为,我设置了默认参数 'a Lazy
除非原始值是 null
,否则不会调用它的源.
示例:
let value = Something.PossiblyNullReturned()
|?? lazy new SameType()
实现:
NullCoalesce.fs [ Gist ]:
//https://gist.github.com/jbtule/8477768#file-nullcoalesce-fs
type NullCoalesce =
static member Coalesce(a: 'a option, b: 'a Lazy) =
match a with
| Some a -> a
| _ -> b.Value
static member Coalesce(a: 'a Nullable, b: 'a Lazy) =
if a.HasValue then a.Value
else b.Value
static member Coalesce(a: 'a when 'a:null, b: 'a Lazy) =
match a with
| null -> b.Value
| _ -> a
let inline nullCoalesceHelper< ^t, ^a, ^b, ^c when (^t or ^a) : (static member Coalesce : ^a * ^b -> ^c)> a b =
// calling the statically inferred member
((^t or ^a) : (static member Coalesce : ^a * ^b -> ^c) (a, b))
let inline (|??) a b = nullCoalesceHelper<NullCoalesce, _, _, _> a b
或者 我制作了一个利用这种技术以及计算表达式来处理 Null/Option/Nullables 的库,名为 FSharp.Interop.NullOptAble
它使用运算符
|?->
反而。
关于f# - F# 中的空合并运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21194565/