OCaml 无法对列表进行排序

OCaml cannot sort lists

我正在尝试在 Ocaml 中对列表(即 'a')进行排序,但我做不到。我具体使用的是内置函数sort(https://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html),使用的变量是'int list'类型的,所以函数内部使用的'compare module'应该没有问题。


我的例子:

尝试时:

sort a

抛出的错误是:

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

其他尝试:

尝试时:

sort [1]

抛出的错误是:

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.

我不明白发生了什么。

提前致谢。

正如 Marth 所说,关键是必须提供比较函数,以指定如何(根据哪个标准)对列表进行排序。

对于最简单的整数情况,使用预定义的compare函数就足够了:

List.sort compare the_list

在其他情况下(取决于 objective),可以使用不同的比较函数,始终考虑到我们要排序的列表中的哪个王。例如,我们可能想要对字符串或其他类型的列表进行排序。