2016-11-05 12 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 [];; 
関連する問題