OCaml stable multi-key sort with nulls last
OCaml
type person = { name : string; age : int option; city : string }
let compare_option compare a b =
match (a, b) with
| None, None -> 0
| Some x, Some y -> compare x y
| None, Some _ -> 1 (* missing values sort last *)
| Some _, None -> -1
let compare_people a b =
match String.compare a.city b.city with
| 0 -> (
match compare_option Int.compare a.age b.age with
| 0 -> String.compare a.name b.name
| other -> other)
| other -> other
let sort_people people = List.stable_sort compare_people people