2012-06-09 16 views
8

que tiene un tipo de registro que incluye una función:Igualdad estructural en F #

{foo : int; bar : int -> int} 

quiero este tipo de tener igualdad estructural. ¿Hay alguna manera en la que pueda marcar que el bar debe ignorarse en las pruebas de igualdad? ¿O hay alguna otra forma de evitar esto?

Respuesta

17

Consulte la publicación de Don blog sobre este tema, específicamente la sección Igualdad personalizada y comparación.

El ejemplo que da es casi idéntica a la estructura de registro que se propone:

/// 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" 
7

Para responder más específicamente a su pregunta original, puede crear un tipo personalizado cuya comparación entre los casos siempre es cierto:

[<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

+1 creativo :-) –