Hacker News new | ask | show | jobs
by chubot 4114 days ago
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.

2 comments

Here's one way to write down the K lines example:

  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.
Idiomatic ocaml would be to use one of those "with" functions whenever possible. Keep in mind that RWO is an introductory book and that they have to show the basics before moving to the larger abstractions...