Sorting List with OCaml standard library function

2019-07-16 03:01发布

问题:

I'm studying OCaml and and doing various exercises on ordering data. I would like to understand how to use the standard librari List for ordering

For example I would like to sort this array using these functions [94; 50; 6; 7; 8; 8]

List.sort 
List.stable_sort 
List.fast_sort 
List.unique_sort

What is the syntax to do it ?

回答1:

If you want to use these functions on your list, you have to specifiy the comparison function.

Quote from the documentation:

The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller

In the module Pervasives you have a polymorphic comparison function:

val compare : 'a -> 'a -> int

So, in your case you can just do:

List.sort compare [94; 50; 6; 7; 8; 8]