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_peopleIn this OCaml version:
We define a
len_comparefunction to compare string lengths, similar to thelenCmpfunction in the original example.We use
List.sortwith our custom comparison function to sort thefruitslist by length.We define a
persontype to represent individuals with a name and age.We create a list of
personvalues.We use
List.sortagain, this time with an inline comparison function that compares theagefield of twopersonvalues.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: 72This 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.