在OCaml中创建直方图
我的任务是创建一个直方图,输出元素在列表中出现的次数在OCaml中创建直方图,ocaml,Ocaml,我的任务是创建一个直方图,输出元素在列表中出现的次数 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)] My code: let rec count a ls = match ls with |[] -> 0 |x::xs wh
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)]
My code:
let rec count a ls = match ls with
|[] -> 0
|x::xs when x=a -> 1 + count a xs
|_::xs -> count a xs
let rec count a = function
|[] -> 0
|x::xs when x=a -> 1 + count a xs
|_::xs -> count a xs
let rec histo l = match l with
|[] -> []
|x :: xs -> [(x, count x l)] @ histo xs ;;
我做错了什么?问题是xs可能包含与x相等的元素。这是您在输出中看到的:(2,3)表示列表中有3乘以2;然后xs等于[2;2;3;4;4;1]。。。等等 另外(不影响结论):您有两个计数定义,但它们是相同的 要实现直方图,请使用Hashtbl:
let h = Hashtbl.create 1000;;
List.iter (fun x -> let c = try Hashtbl.find h x with Not_found -> 0 in Hashtbl.replace h x (c+1)) your_list;;
Hashtbl.fold (fun x y acc -> (x,y)::acc) h [];;
问题是xs可能包含与x相等的元素。这是您在输出中看到的:(2,3)表示列表中有3乘以2;然后xs等于[2;2;3;4;4;1]。。。等等 另外(不影响结论):您有两个计数定义,但它们是相同的 要实现直方图,请使用Hashtbl:
let h = Hashtbl.create 1000;;
List.iter (fun x -> let c = try Hashtbl.find h x with Not_found -> 0 in Hashtbl.replace h x (c+1)) your_list;;
Hashtbl.fold (fun x y acc -> (x,y)::acc) h [];;
您没有从列表中删除已计数的元素,因此它们将被找到并再次计数。知道如何删除它们吗?您没有从列表中删除已计数的元素,因此它们将被找到并再次计数。知道如何删除它们吗?