Sorting in OCaml

OCaml’s standard library provides functions for sorting arrays and lists. We’ll look at sorting for both of these data structures.

(* We'll use the List and Array modules for sorting *)
open List
open Array

let main () =
  (* Sorting functions work for any comparable type.
     For strings, we can use the built-in comparison. *)
  let strs = ["c"; "a"; "b"] in
  let sorted_strs = List.sort String.compare strs in
  Printf.printf "Strings: %s\n" (String.concat " " sorted_strs);

  (* An example of sorting ints *)
  let ints = [|7; 2; 4|] in
  Array.sort compare ints;
  Printf.printf "Ints:    %s\n" (String.concat " " (Array.to_list (Array.map string_of_int ints)));

  (* We can also check if a list or array is already in sorted order *)
  let s = List.is_sorted compare (Array.to_list ints) in
  Printf.printf "Sorted:  %b\n" s

let () = main ()

To run the program, save it as sorting.ml and use the OCaml compiler:

$ ocamlc -o sorting sorting.ml
$ ./sorting
Strings: a b c
Ints:    2 4 7
Sorted:  true

In this OCaml version:

  1. We use the List and Array modules which provide sorting functions.
  2. For strings, we use List.sort with String.compare as the comparison function.
  3. For integers, we use Array.sort with the built-in compare function.
  4. OCaml’s sorting functions are not in-place for immutable data structures like lists, so we bind the result to a new variable.
  5. For arrays, which are mutable, the sort is in-place.
  6. We use List.is_sorted to check if a list is sorted. There’s no built-in function for arrays, so we convert the array to a list first.

Note that OCaml’s standard library doesn’t have a single generic sorting function like Go’s slices.Sort. Instead, you need to provide an appropriate comparison function for each type you want to sort.