gpt4 book ai didi

f# - 对受歧视的联合实现 F# 比较

转载 作者:行者123 更新时间:2023-12-04 01:49:38 25 4
gpt4 key购买 nike

我有一个日志级别类型:

type LoggingLevel =
| Trace
| Debug
| Info

我想说一些日志记录级别高于其他日志记录级别。例如,Trace 高于 Info

所以我这样实现了IComparable:

[<StructuralEqualityAttribute>]
[<CustomComparisonAttribute>]
type LoggingLevel =
| Trace
| Debug
| Info

interface IComparable<LoggingLevel> with
override this.CompareTo other =
let score x =
match x with
| Trace -> 0
| Debug -> 1
| Info -> 2
(score this) - (score other)

但是当我尝试使用它时,出现错误:

if a >= b 
then
// ...

The type 'LoggingLevel' does not support the 'comparison' constraint. For example, it does not support the 'System.IComparable' interface

我这里怎么出错了?


我设法让它工作了,但是现在类型定义太冗长了!一定有更好的方法……

[<CustomEquality>]
[<CustomComparisonAttribute>]
type LoggingLevel =
| Trace
| Debug
| Info

override this.Equals (obj) =
match obj with
| :? LoggingLevel as other ->
match (this, other) with
| (Trace, Trace) -> true
| (Debug, Debug) -> true
| (Info, Info) -> true
| _ -> false
| _ -> false

override this.GetHashCode () =
match this with
| Trace -> 0
| Debug -> 1
| Info -> 2

interface IComparable<LoggingLevel> with
member this.CompareTo (other : LoggingLevel) =
let score x =
match x with
| Trace -> 0
| Debug -> 1
| Info -> 2
(score this) - (score other)

interface IComparable with
override this.CompareTo other =
(this :> IComparable<LoggingLevel>).CompareTo (other :?> LoggingLevel)

最佳答案

I would like to say that some logging levels are higher than others. For example, Trace is higher than Info.

您是否需要使用自定义相等和自定义比较? F# 为可区分联合内置了这些。您只需要在类型定义中按递增顺序编写它们:

type LoggingLevel =
| Info
| Debug
| Trace // Note the order here! 🤔

Trace > Info // true

let levels = [ Trace; Debug; Info; Trace; Debug; Info ]

levels |> List.sort
// [Info; Info; Debug; Debug; Trace; Trace]
// Comparison ✔

levels |> List.countBy id
// [(Trace, 2); (Debug, 2); (Info, 2)]
// Equality ✔

更多信息:https://stackoverflow.com/a/52220335/1256041

关于f# - 对受歧视的联合实现 F# 比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53867688/

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