create a histogram OCaml -
my task create histogram output number of times element in list.
input:[2;2;2;3;4;4;1] output[(2, 3); (2, 2); (2, 1); (3, 1); (4, 2); (4, 1); (1, 1)] expected output : [(2, 3); (3, 1); (4, 2); (1, 1)] code: let rec count ls = match ls |[] -> 0 |x::xs when x=a -> 1 + count xs |_::xs -> count xs let rec count = function |[] -> 0 |x::xs when x=a -> 1 + count xs |_::xs -> count xs let rec histo l = match l |[] -> [] |x :: xs -> [(x, count x l)] @ histo xs ;;
what have done wrong?
the issue xs contains potentially elements equal x. see in ouput : (2,3) means there 3 times 2 in list; xs equals [2;2;3;4;4;1]... , on.
also (not impacting conclusion): have 2 definitions of count, identical.
to implement histogram, use hashtbl :
let h = hashtbl.create 1000;; list.iter (fun x -> let c = try hashtbl.find h x not_found -> 0 in hashtbl.replace h x (c+1)) your_list;; hashtbl.fold (fun x y acc -> (x,y)::acc) h [];;
Comments
Post a Comment