Jackson Tale
Jackson Tale

Reputation: 25812

How to write the function `compare : 'a -> 'a -> int` in OCaml?

Well, the title of this question explains itself.

In Pervasives, compare function is external.

What if I am asked to implement such a function in OCaml? Is that possible?

Upvotes: 1

Views: 360

Answers (1)

Martin Jambon
Martin Jambon

Reputation: 4899

It is not possible.

We cannot implement in OCaml functions that are both polymorphic and inspect the data corresponding to the type parameter. The Obj module can make this possible but it is "not part of the OCaml language" (X. Leroy).

Pervasives.compare is implemented in C and could be implemented similarly using the Obj module. It relies on the runtime representation of OCaml values, and as a consequence the order cannot be customized on a per-type basis without extra tagging.

Upvotes: 4

Related Questions