Equality Tests and Member
Polymorphic equality
OCaml provides polymorphic equality operators that work across many types without requiring explicit type-specific comparison functions:
| Operator | Meaning |
|---|---|
= | Structural equality |
<> | Structural inequality |
< | Less than (structural ordering) |
<= | Less than or equal |
> | Greater than |
>= | Greater than or equal |
These operators inspect the structure of values and apply a consistent ordering.
The member function
member uses linear search with polymorphic equality to test whether a value appears in a list:
let rec member x = function
| [] -> false
| y::l ->
if x = y then true
else member x l
Its type, 'a -> 'a list -> bool, reflects that it works for any type that supports polymorphic equality.
Which types support it?
| Supported | Not supported |
|---|---|
| Integers | Functions |
| Strings | Recursive structures (in general) |
| Booleans | Abstract types without comparison |
| Tuples of primitive types | |
| Lists of primitive types |
Limitations and controversy
Polymorphic equality cannot compare function values: two functions that compute the same result from identical source code may be stored at different memory addresses, and OCaml has no principled way to test functional equivalence.
The presence of polymorphic equality is contentious in the OCaml community. For small programs and learning, it is convenient and safe enough. In large systems, however, its use can mask bugs: it may compare values that should not be compared, or impose structural ordering where none is meaningful. Many large-scale OCaml codebases avoid it in critical paths, preferring explicit comparison functions passed as arguments. For the purposes of this course, polymorphic equality is sufficient.