本文介绍了F#中的结构相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含函数的记录类型:
I have a record type that includes a function:
{foo : int; bar : int -> int}
我希望这种类型具有结构上的相等性.有什么方法可以让我标记在相等性测试中应该忽略bar
吗?还是有其他解决方法?
I want this type to have structural equality. Is there some way I can just mark that the bar
should be ignored in equality tests? Or is there some other way around this?
推荐答案
请参见Don的博客帖子,特别是自定义平等和比较部分.
See Don's blog post on this topic, specifically the section Custom Equality and Comparison.
他提供的示例与您建议的记录结构几乎相同:
The example he gives is almost identical to the record structure you propose:
/// A type abbreviation indicating we’re using integers for unique stamps on objects
type stamp = int
/// A type containing a function that can’t be compared for equality
[<CustomEquality; CustomComparison>]
type MyThing =
{ Stamp: stamp;
Behaviour: (int -> int) }
override x.Equals(yobj) =
match yobj with
| :? MyThing as y -> (x.Stamp = y.Stamp)
| _ -> false
override x.GetHashCode() = hash x.Stamp
interface System.IComparable with
member x.CompareTo yobj =
match yobj with
| :? MyThing as y -> compare x.Stamp y.Stamp
| _ -> invalidArg "yobj" "cannot compare values of different types"
这篇关于F#中的结构相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!