f# - 使用不区分大小写的比较从集合中减去记录

标签 f# record string-comparison

我有一组记录:

type Person =
    {
        Name : string
        Age : int
    }


let oldPeople =
    set [ { Name = "The Doctor"; Age = 1500 };
          { Name = "Yoda";       Age = 900 } ]

与上面的硬编码示例不同,数据集实际上来自数据源(我几乎无法控制)。现在我需要从另一个数据源中减去一组数据。一般来说,第二个源中的数据是匹配的,但偶尔会出现大小写差异:

let peopleWhoAreConfusedAboutTheirAge =
    set [ { Name = "THE DOCTOR"; Age = 1500 } ]

当我尝试从第一个集合中减去第二个集合时,它失败了,因为字符串比较区分大小写:

let peopleWhoKnowHowOldTheyAre =
    oldPeople - peopleWhoAreConfusedAboutTheirAge
val peopleWhoKnowHowOldTheyAre : Set<Person> =
  set [{Name = "The Doctor";
        Age = 1500;}; {Name = "Yoda";
                       Age = 900;}]

有没有办法对 People 记录的 Name 字段执行不区分大小写的比较?

最佳答案

这是我到目前为止所实现的,尽管可能有更好的方法来做到这一点。

我的解决方案是覆盖 People 记录上的 Equals 函数,以便执行不区分大小写的比较。集合减法使用 Equals 函数来确定两条记录是否相互匹配。通过覆盖 Equals,我被迫(通过警告和错误)覆盖 GetHashCode 并实现 IComparable(以及设置 CustomEquality CustomComparison 属性):

[<CustomEquality; CustomComparison>]
type Person =
    {
        Name : string
        Age : int
    }

    member private this._internalId =
        this.Name.ToLower() + this.Age.ToString()

    interface System.IComparable with
        member this.CompareTo obj =
            let other : Person = downcast obj
            this._internalId.CompareTo( other._internalId )

    override this.Equals( other ) =
        match other with
        | :? Person as other -> 
            System.String.Compare( this._internalId, other._internalId ) = 0
        | _ -> false

    override this.GetHashCode() =
        this._internalId.GetHashCode()

然而,这似乎可以解决问题:

let oldPeople =
    set [ { Name = "The Doctor"; Age = 1500 };
          { Name = "Yoda";       Age = 900 } ]

let peopleWhoAreConfusedAboutTheirAge =
    set [ { Name = "THE DOCTOR"; Age = 1500 } ]

let peopleWhoKnowHowOldTheyAre =
    oldPeople - peopleWhoAreConfusedAboutTheirAge
val peopleWhoKnowHowOldTheyAre : Set<Person> = set [{Name = "Yoda";
                                                     Age = 900;}]

如果您知道更好的解决方案(涉及更少的代码),请发布它而不是对此答案发表评论。我很乐意接受一个不那么冗长、笨拙的解决方案。

关于f# - 使用不区分大小写的比较从集合中减去记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21839463/

相关文章:

f# - F# 和 C# lambda 之间的互操作

Delphi - 将记录作为窗口消息发送

c++ - strcmp 或字符串::比较?

bash - bash 中的字符串比较。 [[ : not found

php - 比较字符串,在 PHP 中使用 == 包含空格

f# - 如果F#支持void类型,为什么我需要使用单位类型?

c# - F# 按多个值进行分组并聚合

f# - 增强了可区分联合的调试信息

MySQL 记录磁盘使用计算 |我对吗?

记录 R 中循环的输出