Using the F # hash function inside GetHashCode () is evil?

I came across several places on the Internet where the code looked something like this:

[<CustomEquality;NoComparison>]
type Test =
    | Foo
    | Bar
    override x.Equals y = 
        match y with
        | :? Test as y' ->
            match y' with
            | Foo -> false
            | Bar -> true    // silly, I know, but not the question here
        | _ -> failwith "error"   // don't do this at home

    override x.GetHashCode() = hash x

But when I run the above in FSI, the invitation does not return when I either call hash fooin the instance Test, or when I call foo.GetHashCode()directly.

let foo = Test.Foo;;
hash foo;;   // no returning to the console until Ctrl-break
foo.GetHashCode();;  // no return

I could not readily confirm this, but it assumes that it hash xis calling GetHashCode()on the object, which means that the above code is dangerous. Or is it just an FSI game?

I thought that code like the one above only means “perform normal equality, but leave the default hash function”.

-, , , hash GetHashCode(), .


, FSI , , GetHashCode() , - . : , x.Equals GetHashCode(), Equals, GetHashCode().

+4
2

, hash, GetHashCode, , : override x.GetHashCode() = hash x.

hash, :

let rec GenericHashParamObj (iec : System.Collections.IEqualityComparer) (x: obj) : int =
    match x with 
    | null -> 0 
    | (:? System.Array as a) -> 
        match a with 
        | :? (obj[]) as oa -> GenericHashObjArray iec oa 
        | :? (byte[]) as ba -> GenericHashByteArray ba 
        | :? (int[]) as ba -> GenericHashInt32Array ba 
        | :? (int64[]) as ba -> GenericHashInt64Array ba 
        | _ -> GenericHashArbArray iec a 
    | :? IStructuralEquatable as a ->    
        a.GetHashCode(iec)
    | _ -> 
        x.GetHashCode()

, x.GetHashCode(), .

, , hash GetHashCode(), , -.

( ) hash GetHashCode() Don Syme WebLog.


, , , .

object.Equals . , false. System.Object.

; . , obj null, Equals false , ArgumentNullException.

()

+5

GetHashCode() , hash :

[ hash -, - , =. F #, , . , System.Object.GetHashCode .

, , , , .

+5

Source: https://habr.com/ru/post/1655746/


All Articles