Is this really happening?
No.
Pervasives.compare is run using external .
I think this applies to compare.c , which implements a string case using
#define LESS -1 #define EQUAL 0 #define GREATER 1 mlsize_t len1 = caml_string_length(v1); mlsize_t len2 = caml_string_length(v2); int res = memcmp(String_val(v1), String_val(v2), len1 <= len2 ? len1 : len2); if (res < 0) return LESS; if (res > 0) return GREATER; if (len1 != len2) return len1 - len2;
Thus, it seems that it really can return an arbitrary integer for strings such as compare "a" "abc" ( -2 ).
But if we try in Ocaml, this will not happen and just return -1 . Why not?
Since the real comparison function , which is exposed to the Ocaml code, normalizes the results:
CAMLprim value caml_compare(value v1, value v2) { intnat res = compare_val(v1, v2, 1); if (res < 0) return Val_int(LESS); else if (res > 0) return Val_int(GREATER); else return Val_int(EQUAL); }
So it really cannot return any int other than the three.
source share