OCaml无法对列表进行排序

问题描述

我正在尝试对Ocaml中的列表(即“ a”)进行排序,但是我不能。我具体使用内置函数sort(https://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html),并且所使用的变量的类型为“ int列表”,因此该函数在内部使用的“比较模块”应该没有任何问题。>


我的例子:

尝试时:

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

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