2016-11-10 40 views
1

Hy,我想創建一個直方圖,但我不斷收到錯誤。錯誤使用List.filter OCaml

Histogram example: 
input :[2;1;2;3;2;1;2;2;5] 
output :[(2,5);(1,2);(3,1);(5,1)] 

我的代碼:

let rec count a ls = match ls with 
    |[]    -> 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)] @ List.filter(fun x -> xs != x)histo xs;; 

錯誤: 這個函數的類型是( 'A - >布爾) - >' 列表 - >「它是適用於太多的參數列表;也許你忘了';'。

+1

'List.filter(有趣X! - > XS = X)(HISTO XS)' – beoliver

回答

1

你幾乎在最後;) 一些提示:

  • 照顧括號的(有些是缺少在代碼中)。
  • 你的過濾器是不正確的:(fun(t,_) - > not(t = x)),因爲histo返回一個元組列表。
0
let rec count a = function 
    |[] -> 0 
    |x::xs -> if x=a then 1 + count a xs else count a xs 

let rec histo = function 
    |[] -> []  
    |x::xs -> let l'=List.filter ((<>)x) xs in 
      [(x, 1+count x xs)] @ histo l' 
;; 

測試

# histo [2;1;2;3;2;1;2;2;5];; 
- : (int * int) list = [(2, 5); (1, 2); (3, 1); (5, 1)] 

或者

let rec histo = function 
    |[] -> [] 
    |x::xs -> let l'=List.filter ((<>)x) xs in 
      [(x, 1+List.length xs - List.length l')] @ histo l' 
;;