8
我有一個包括功能的記錄類型:結構相等的F#
{foo : int; bar : int -> int}
我想這種類型的有結構相等。有什麼方法可以標記在平等測試中bar
應該被忽略嗎?或者還有其他解決方法嗎?
我有一個包括功能的記錄類型:結構相等的F#
{foo : int; bar : int -> int}
我想這種類型的有結構相等。有什麼方法可以標記在平等測試中bar
應該被忽略嗎?或者還有其他解決方法嗎?
請參閱Don的blog關於此主題的帖子,具體爲自定義平等和比較。
他給出的例子幾乎是相同的,你提出的記錄結構:
/// 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"
要回答更具體的你原來的問題,您可以創建一個自定義類型的實例之間,其對比始終是真實的:
[<CustomEquality; NoComparison>]
type StructurallyNull<'T> =
{ v: 'T }
override x.Equals(yobj) =
match yobj with
| :? StructurallyNull<'T> as y -> true
| _ -> false
override x.GetHashCode() = 0
type MyType = {
foo: int;
bar: StructurallyNull<int -> int>
}
+1 creative :-) –