2016-11-05 64 views
0

我的任務是創建一個直方圖,輸出它在列表中的元素的次數。創建直方圖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 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 ;; 

我做錯了什麼?

+0

你不是從列表中刪除的計元素,所以他們會被發現並重新計數。 – melpomene

+0

任何想法如何刪除它們? –

回答

2

問題是xs包含的潛在元素等於x。這是你在輸出中看到的內容:(2,3)表示列表中有3次2;那麼xs等於[2; 2; 3; 4; 4; 1] ...等等。

另外(不影響結論):你有2個定義的計數,但它們是相同的。

要實現直方圖,使用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 [];;