f# - F# 中的空合并运算符?

标签 f# null null-coalescing-operator null-coalescing

在与 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/

相关文章:

.net - 如何有效地编写 F# 程序集以实现部分信任?

list - F#'s list is eager or lazy evaluated? Or only "seq"在 F# 中延迟求值

java - 方法返回 null 并尝试调用方法

javascript - Null-Coalescing Operator (??) 在 Spider 中是如何工作的?

c# - 可以用吗?? (合并运算符)与 DBNull?

f# - 为什么 F# 交互式控制台不认为 "assert (2=3)"是错误的?

data-structures - 使用 F# 联合查找

C++ double* 数组,测试分配

java - 链表 : What to substitute for node on the last node?

c# - 使用空合并运算符进行比较