gpt4 book ai didi

generics - 具有静态解析类型参数的类型的自定义相等性

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

如何使用静态解析的类型参数在 F# 类型中实现自定义相等方法?

我试过这样做:

[<CustomEqualityAttribute>]
type Fraction< ^a when ^a: equality and ^a : (static member (*): ^a * ^a -> ^a) > (nominator: ^a, denominator: ^a) =
member inline this.Nominator = nominator
member inline this.Denominator = denominator

member inline this.IsEqualTo(other: Fraction< ^a >) = this.Nominator * other.Denominator = other.Nominator * this.Denominator

override inline this.Equals(other: obj) =
match obj with
| :? Fraction< ^a > as f -> this.IsEqualTo(f)
| _ -> false

我在 this.Equals 上收到以下错误线:

This member, function or value declaration may not be declared 'inline'



这是为什么?是不是因为 Equals是覆盖吗?如果是这种情况,是否有任何方法可以实现自定义相等性,或者我是否被迫使用 IEqualityComparer ?

最佳答案

Why is that? Is it because the Equals is an override?



是的。安 inline类的方法不是该类的实际方法。相反,在某处对该方法的每次调用都将被解释为它的实现(与 C++ 非常相似)。由于您要覆盖 Equals方法是一个实际的方法(来自 Object 类),你不能让它 inline .

If that's the case, is there any way at all to implement the custom equality?



您可以从类型中提取具体的乘法,因此您不会被迫使用 inlineEquals方法:
[<CustomEquality; NoComparison>]
type Frac<'T when 'T : equality> = private {
nominator : 'T
denominator : 'T
mult : 'T -> 'T -> 'T
} with
member x.Nominator = x.nominator
member x.Denominator = x.denominator
override x.Equals other =
match other with
| :? Frac<'T> as o ->
let ( * ) = x.mult in x.nominator * o.denominator = o.nominator * x.denominator
| _ -> false
static member inline Create x y = { nominator = x; denominator = y; mult = ( * ) }
// Test
Frac.Create 1 2 = Frac.Create 3 6 // true
Frac.Create 1.0 2.0 = Frac.Create 3.0 7.0 // false
Frac.Create 1 2 = Frac.Create 3.0 6.0 // compile error

关于generics - 具有静态解析类型参数的类型的自定义相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56115210/

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