Sorting List with OCaml standard library function

16,088

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]
Share:
16,088
daniele3004
Author by

daniele3004

Yeppa

Updated on July 24, 2022

Comments

  • daniele3004
    daniele3004 almost 2 years

    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 ?

  • daniele3004
    daniele3004 over 9 years
    You can also add the descending sort with compare function?
  • daniele3004
    daniele3004 over 9 years
    Perfect:-) for descending "let myCompare x y = if x<y then 1 else -1;;" I missed this step. thanks
  • nlucaroni
    nlucaroni over 9 years
    That will mostly work, but myCompare 1 1 will return -1. You can always do, (fun x y -> ~- (compare x y)).