gpt4 book ai didi

F# -> 为 HashSet<'a> 实现 IComparable

转载 作者:行者123 更新时间:2023-12-03 18:16:49 27 4
gpt4 key购买 nike

是否有可能以某种方式实现 IComparable对于 HashSet<'a> ?原因是我声明了以下记录:

[<StructuralComparison>]
type Category = {
mutable Id: string;
Name: string;
SavePath: string;
Tags: HashSet<Tag> }

and Tag = { Tag:string; }

如您所见,然后在 Category 中添加标签记录类型为 HashSet<Tag> - 为了将一系列类别映射到 map ,我需要实现 IComparable不知何故......否则它只会导致:

The struct, record or union type 'Category' has the 'StructuralComparison' attribute but the component type 'HashSet' does not satisfy the 'comparison'



请注意,除了 HashSet<'a> 我不能使用其他任何东西因为我正在使用的数据库完全理解任何 fsharp-ish 列表。

最佳答案

我假设你想比较和等同 Category s 只服用 Id , Name , 和 SavePath考虑到(按该顺序),使记录表现得好像 Tags不在场:

open System
open System.Collections.Generic

[<CustomComparison; CustomEquality>]
type Category =
{ mutable Id : string;
Name : string;
SavePath : string;
Tags : HashSet<Tag> }
member private this.Ident = this.Id, this.Name, this.SavePath
interface IComparable<Category> with
member this.CompareTo other =
compare this.Ident other.Ident
interface IComparable with
member this.CompareTo obj =
match obj with
| null -> 1
| :? Category as other -> (this :> IComparable<_>).CompareTo other
| _ -> invalidArg "obj" "not a Category"
interface IEquatable<Category> with
member this.Equals other =
this.Ident = other.Ident
override this.Equals obj =
match obj with
| :? Category as other -> (this :> IEquatable<_>).Equals other
| _ -> false
override this.GetHashCode () =
hash this.Ident

and Tag = { Tag : string; }

但是,如果您想通过 Name 进行比较并等于 Id然后考虑以下事项:
open System
open System.Collections.Generic

[<CustomComparison; CustomEquality>]
type Category =
{ mutable Id : string;
Name : string;
SavePath : string;
Tags : HashSet<Tag> }
interface IComparable<Category> with
member this.CompareTo { Name = name } =
this.Name.CompareTo name
interface IComparable with
member this.CompareTo obj =
match obj with
| null -> 1
| :? Category as other -> (this :> IComparable<_>).CompareTo other
| _ -> invalidArg "obj" "not a Category"
interface IEquatable<Category> with
member this.Equals { Id = id } =
this.Id = id
override this.Equals obj =
match obj with
| :? Category as other -> (this :> IEquatable<_>).Equals other
| _ -> false
override this.GetHashCode () =
this.Id.GetHashCode ()

and Tag = { Tag : string; }

关于F# -> 为 HashSet<'a> 实现 IComparable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5557899/

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