FWIW I took it straight out of Real World OCaml, assuming that that's idiomatic OCaml.
See my other comment -- how does top K lines in OCaml look? I recall that was in the book too, but couldn't find it. I remember it being fantastically ugly.
See my other comment -- how does top K lines in OCaml look? I recall that was in the book too, but couldn't find it. I remember it being fantastically ugly.
let top_k chan k =
let incr_count m l =
let n = try Map.find_exn m l with Not_found -> 0 in
Map.add m ~key:l ~data:(n + 1)
in
In_channel.input_lines chan
|> List.fold ~init:String.Map.empty ~f:incr_count
|> Map.to_alist
|> List.sort ~cmp:(fun (_,a) (_,b) -> compare b a)
|> List.sub ~pos:0 ~len:k
You could probably code-golph it down to a couple of lines but I find the 'pipe' operator leads to very readable code.