(* wp * * compile with: * ocamlopt.opt str.cmxa -o wp_ml wp.ml * *) open Str let print_hash hash = let rhash = Hashtbl.create (Hashtbl.length hash) in Hashtbl.iter ( fun key value -> let keylst = try Hashtbl.find rhash value with Not_found -> [] in Hashtbl.replace rhash value (key::keylst); ) hash; let lst = Hashtbl.fold ( fun key _ lst -> key::lst) rhash [] in let sorted_list = List.fast_sort (fun a b -> compare b a) lst in List.iter ( fun rkey -> List.iter ( fun rvalue -> Printf.printf "'%s' -> %i\n" rvalue rkey ) (Hashtbl.find rhash rkey) ) sorted_list let split_line s = let r = ref [] in let j = ref (String.length s) in for i = String.length s - 1 downto 0 do if s.[i] = ' ' || s.[i] = '\t' then begin r := String.sub s (i + 1) (!j - i - 1) :: !r; j := i end done; String.sub s 0 !j :: !r let _ = let hash = Hashtbl.create 131072 in try let re = Str.regexp "[ \t]+" in while true do let words = split_line (read_line ()) in List.iter (fun w -> let n = try Hashtbl.find hash w with Not_found -> 0 in Hashtbl.replace hash w (succ n) ) words done with End_of_file -> print_hash hash