Title here
Summary here
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:
List
and Array
modules which provide sorting functions.List.sort
with String.compare
as the comparison function.Array.sort
with the built-in compare
function.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.