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