Late answer, but with Hashtbl
s you can have a good performance, according to the benchmarks here count unique elements in list in OCaml.
Then, adding a simple sort on the elements and their number of occurences, you obtain the most common element in the list.
module IntHash =
struct
type t = int
let equal i j = i=j
let hash i = i land max_int
end
module IntHashtbl = Hashtbl.Make(IntHash)
let count_unique_elements_int_hashtbl list =
let counter = IntHashtbl.create 10000 in
let update_counter x =
if IntHashtbl.mem counter x then
let current_count = IntHashtbl.find counter x in
IntHashtbl.replace counter x (succ current_count)
else
IntHashtbl.replace counter x 1
in
List.iter update_counter list;
IntHashtbl.to_seq counter
|> List.of_seq
let most_common_element_in_int_list list =
count_unique_elements_int_hashtbl list
|> List.sort (fun x y -> compare (snd x) (snd y))
|> List.rev
|> List.hd
|> fst
let () =
assert (most_common_element_in_int_list [1;2;1] = 1);
assert (most_common_element_in_int_list [6;1;2;1;6;6] = 6);