Sorting By Functions in OCaml

Here’s the OCaml translation of the Go code for sorting by functions:

Our example demonstrates custom sorting in OCaml. We’ll sort strings by their length and then sort a list of custom structures.

open List

(* We'll use this to compare string lengths *)
let len_compare a b = compare (String.length a) (String.length b)

let () =
  let fruits = ["peach"; "banana"; "kiwi"] in

  (* Sort fruits by length *)
  let sorted_fruits = List.sort len_compare fruits in
  Printf.printf "Sorted fruits: %s\n" (String.concat ", " sorted_fruits);

  (* Define a Person type *)
  type person = { name : string; age : int }

  (* Create a list of people *)
  let people = [
    { name = "Jax"; age = 37 };
    { name = "TJ"; age = 25 };
    { name = "Alex"; age = 72 }
  ]

  (* Sort people by age *)
  let sorted_people = List.sort (fun a b -> compare a.age b.age) people in

  (* Print sorted people *)
  List.iter (fun p -> Printf.printf "%s: %d\n" p.name p.age) sorted_people

In this OCaml version:

  1. We define a len_compare function to compare string lengths, similar to the lenCmp function in the original example.

  2. We use List.sort with our custom comparison function to sort the fruits list by length.

  3. We define a person type to represent individuals with a name and age.

  4. We create a list of person values.

  5. We use List.sort again, this time with an inline comparison function that compares the age field of two person values.

  6. Finally, we print the sorted lists to show the results.

To run this program, save it to a file (e.g., sorting_by_functions.ml) and compile it using the OCaml compiler:

$ ocamlc -o sorting_by_functions sorting_by_functions.ml
$ ./sorting_by_functions
Sorted fruits: kiwi, peach, banana
TJ: 25
Jax: 37
Alex: 72

This example demonstrates how to implement custom sorting in OCaml using the List.sort function with custom comparison functions. It’s a powerful and flexible way to sort collections based on specific criteria.