gpt4 book ai didi

.net - F# 比较区分联合的案例标识符

转载 作者:行者123 更新时间:2023-12-04 22:31:13 25 4
gpt4 key购买 nike

有没有办法通过 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 函数?

IE。类似于以下内容,但更通用(反射没问题):
let compareCases a b =
match a with
| MyString(_) -> match b with | MyString(_) -> true | _ -> false
| MyInt(_) -> match b with | MyInt(_) -> true | _ -> false

最佳答案

使用 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)

关于.net - F# 比较区分联合的案例标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23796457/

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