简体   繁体   中英

OCaml cannot sort lists

I am trying to sort a list (ie '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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM