4

有没有办法通过 F# 中的案例标识符来比较有区别的联合?

type MyUnion =
| MyString of string
| MyInt of int

let x = MyString("hello")
let y = MyString("bye")
let z = MyInt(25)

let compareCases a b =
// compareCases x y = true
// compareCases x z = false
// compareCases y z = false

如何compareCases以通用方式实现功能?

即类似于以下内容,但更通用(反射是可以的):

let compareCases a b =
  match a with
  | MyString(_) -> match b with | MyString(_) -> true | _ -> false
  | MyInt(_) -> match b with | MyInt(_) -> true | _ -> false
4

4 回答 4

6

使用 GetType() 的问题是,如果您有 2 个“无数据”案例,它会失败。

这是一种方法:(编辑,因为以前的 UnionTagReader 没有被缓存)

type MyDU =
    | Case1
    | Case2
    | Case3 of int
    | Case4 of int

type TagReader<'T>() =
    let tr = 
        assert FSharpType.IsUnion(typeof<'T>)
        FSharpValue.PreComputeUnionTagReader(typeof<'T>, System.Reflection.BindingFlags.Public)

    member this.compareCase (x:'T) (y:'T) =
        (tr x) = (tr y)

let tr = TagReader<MyDU>()

let c1 = Case1
let c2 = Case2
let c3 = Case3(0)
let c3' = Case3(1)
let c4 = Case4(0)

assert (c1.GetType() = c2.GetType() )  //this is why you can not use GetType()

assert tr.compareCase c1 c1
assert not (tr.compareCase c1 c2)
assert tr.compareCase c3 c3'
assert not (tr.compareCase c3 c4)
于 2014-05-22T19:34:36.017 回答
4

首先,您可以像这样改进您的示例:

let compare = function
| MyString _, MyString _, | MyInt _, MyInt _ -> true
| _ -> false

但这是最好的方法(反射最少!):

let compare a b = a.GetType () = b.GetType ()
于 2014-05-22T05:11:44.497 回答
1

这应该可以解决问题

open Microsoft.FSharp.Reflection

type MyUnion =
    | MyString of string
    | MyInt of int

let x = MyString("hello")
let y = MyString("bye")
let z = MyInt(25)

let compareCases a b =
    FSharpValue.GetUnionFields (a, a.GetType()) |> fst
        = (FSharpValue.GetUnionFields (b, b.GetType()) |> fst)

但是,为了对这些值做任何事情,您仍然需要进行模式匹配,所以说实话,我不太明白这一点。

于 2014-05-22T05:07:46.747 回答
0
let compareCases (a : MyUnion) (b : MyUnion) =
    a.GetType().Name = b.GetType().Name
于 2014-05-22T09:37:26.287 回答