Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does compare work for all types?

Tags:

ocaml

Let's consider a type t and two variables x,y of type t.

Will the call compare x y be valid for any type t? I couldn't find any counterexample.

like image 343
marmistrz Avatar asked Dec 29 '15 15:12

marmistrz


1 Answers

The polymorphic compare function works by recursively exploring the structure of values, providing an ad-hoc total ordering on OCaml values, used to define structural equality tested by the polymorphic = operator.

It is, by design, not defined on functions and closures, as observed by @antron. The recursive nature of the definition implies that structural equality is not defined on values containing a function or a closure. This recursive nature also imply that the compare function is not defined on recursive values, as mentioned by a @antron as well.

Structural equality, and therefore the compare function and the comparison operators, is not aware of structure invariants and cannot be used to compare (mildly) advanced data structures such as Sets, Maps, HashTbls and so on. If comparison of these structures is desired, a specialised function has to be written, this is why Set and Map define such a function.

When defining your own structures, a good rule of thumb is to distinguish between

  • concrete types, which are defined only in terms of primitive types and other concrete types. Concrete types should not be used for structures whose processing expects some invariants, because it is easy to create arbitrary values of this type breaking these invariants. For these types, the polymorphic comparison function and operators are appropriate.

  • abstract types, whose concrete definition is hidden. For these types, it is best to provide specialised comparison function. The mixture library defines a compare mixin that can be used to derive comparison operators from the implementation of a specialised compare function. Its use is illustrated in the README.

like image 90
Michaël Le Barbier Avatar answered Oct 16 '22 01:10

Michaël Le Barbier