1
我想在F#中實現一個類型Symbol
,它有一個關聯的字符串和位置(比如說文本中的行號)。我會做如下:爲什麼在F#中CustomEquality和CustomComparison有兩種不同的語法?
type Symbol = Symbol of string * int // (string, line number)
我想要一個自定義的平等,關閉行號。我會有一個「嚴格的平等」,考慮到行號,但我希望默認的平等比較隻字符串。看着this SO post,似乎一個人必須做如下:
[<CustomEquality; CustomComparison>]
type Symbol =
| Symbol of string * int
member x.GetString() =
match x with
| Symbol (s, _) -> s
override x.Equals(y) = // Equality only compares strings, not positions.
match y with
| :? Symbol as i -> i.GetString() = x.GetString()
| _ -> false
override x.GetHashCode() =
match x with
| Symbol (s, p) -> hash (s, p)
但是,要實現自定義的比較,必須加上上述聲明
interface System.IComparable with
member x.CompareTo(yobj) =
match yobj with
| :? Symbol as y -> compare (x.GetString()) (y.GetString())
| _ -> invalidArg "yobj" "cannot compare values of different types"
我爲什麼寫override x.Equals(y)...
以下,但不override x.CompareTo(yobj)...
?爲什麼我必須指定interface System.IComparable with ...
?它似乎存在System.IEquatable
,但我不需要指定它,爲什麼?這不是一個很大的區別,但我只是想知道爲什麼差異在這裏。