0
votes

I am trying to sort a list (i.e 'a') in Ocaml but I cannot. I concretely use the built-in function sort (https://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html) and the used variable is of the type 'int list', so there should not be any problem with the 'compare module' that the function uses inside.


My example:

When trying:

sort a

The thrown error is:

This expression has type int list but an expression was expected of type 'a -> 'a -> int

Other attempts:

When trying:

sort [1]

The thrown error is:

This expression has type 'a List.t = 'a list but an expression was expected of type 'b -> 'b 
-> int List.t is abstract because no corresponding cmi file was found in path.

I do not understand what happens.

Thanks in advance.

1
You need to pass the comparison function as the fist argument (the 'a -> 'a -> int). - Marth
Thank you very much! So would it be 'sort cmp a'? By the way is there any good built-in comparison function for integers? I only find implementations like (discuss.ocaml.org/t/canonical-way-to-write-a-compare-function/…) and in merge in (caml.inria.fr/pub/docs/manual-ocaml/libref/List.html) they talk about one cmp. - Theo Deep
You can use the compare function from pervasives, using it as List.sort compare [2; 3; 1];;. For more complicated/custom types you're probably better off using a cmp function (that is, a function 'a -> 'a -> int where the result is greater than 0 if the first is greater that the second one, less than 0 if it's the other way around and 0 if both values are equals (or "considered equals" in this comparison)). Note that compare will work on most types, but I wouldn't use it for anything but primitives. - Marth
It worked! 'sort compare a' worked, as well as with an own 'cmp'. Gonna use compare for the primitives, and construct similar functions for my own types. Thanks very much again! - Theo Deep

1 Answers

0
votes

As Marth says, the point is that a comparison function has to be provided, in order to specify HOW (with which criteria) the list will be sorted.

For the simplest cases of integers, it is enough to use the predefined compare function:

List.sort compare the_list

In other cases (depending on the objective), different comparison functions can be used, always taking into account which king of list we want to sort. For instance, we may want to sort a list of string or another type.