4 ms·
Your comparison isn't really fair. With similar functions from Core's In_channel you can write something like: let sum_file filename = with_file filename
by l_dopa 12y ago
Your comparison isn't really fair. With similar functions from Core's In_channel you can write something like:
let sum_file filename =
with_file filename
(fold_lines ~init:0 ~f:(fun a l -> a + int_of_string l))
"Using the right tool for the job" when it comes to functional vs. "mainstream" languages is a popular meme, but it doesn't hold up to scrutiny. You can always write your own higher-level code for a given domain with a reasonably expressive language. Adding a useful type system, ADTs, etc. to a language like Python is much, much harder (though that's exactly what Microsoft and Google are trying with Javascript).
- chubot 12y agoFWIW 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.
- ufo 12y agoIdiomatic 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...
- l_dopa 12y agoHere'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.