1
votes

Hy, i'm trying to create a histogram but i keep getting an error.

Histogram example:
input :[2;1;2;3;2;1;2;2;5]
output :[(2,5);(1,2);(3,1);(5,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 histo l = match l with
|[] -> []
|x :: xs ->  [(x, count x l)] @ List.filter(fun x -> xs != x)histo xs;;

Error: This function has type ('a -> bool) -> 'a list -> 'a list It is applied to too many arguments; maybe you forgot a `;'.

2
List.filter (fun x -> xs != x) (histo xs) - beoliver

2 Answers

1
votes

You are almost at the end ;) Some hints :

  • take care of parenthesis (some are missing in your code).
  • your filter is not correct : (fun (t,_) -> not (t = x)) because histo returns a list of tuple.
0
votes
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'
;; 

Test

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

Or

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