Version franēaise
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
Annoying behaviour of OCaml
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2008-01-10 (14:43)
From: Thomas Fischbacher <tf@f...>
Subject: Annoying behaviour of OCaml

Yesterday, we were bitten quite badly by a rude surprise where OCaml
behaved in a rather different way from what we would have expected:


compare "cat" "dog";; (* gives -1, just as strcmp would do *)

compare "def" "abcde";; (* gives 1, again, as expected *)

compare (1,5) (1,7);;  (* gives -1, comparison seems to be
			  lexicographic on containers... *)

compare [|1;2;3|] [|4;5|];; (* ...but actially is not: this gives 1,
			       supposedly because the second list is
			       shorter than the first.

compare ((17,23),[|8;9;10|]) ((12,21),[|8;9|]);;

(* This situation is quite similar to the one where encountered
    the problem. We tried to use Array.sort in conjunction with
    "compare" to sort some abstract specifications of contributions
    to a sparse matrix of the form ((row,column),array_of_factors)
    by row, assuming that "compare" would do the job through
    lexicographical order, but actually, it does not. In this case,
    the result is +1 rather than -1!

compare ((17,23),[8;9;10]) ((12,21),[8;9]);;

(* Interestingly, this also gives +1, so using "compare" and replacing
    arrays by lists commutes. This is rather strange, as walking a list
    to determine its length certainly is more effort than implementing
    lexicographical comparison...


Let us see for comparison how other H.M.-typed languages behave:
Haskell (hugs):

Haskell 98 mode: Restart with command line option -98 to enable extensions

Type :? for help
Hugs.Base> ((17,23),[8,9,10]) < ((12,21),[8,9])

...just as about everybody would expect.

SML, by the way, does not seem to extend ">" to container types.

I think it would be a *very* good idea to provide
compare_lexicographically in addition to compare as a pre-defined built-in,
as this is (1) what many people want to do, (2) it cannot be implemented
without resorting to either C or black magic, and (3) it would not change
the behaviour of already existing code that uses "compare".

best regards,
Thomas Fischbacher