How to search and count duplicates in a list

Finding and counting duplicates:
let rec countDupInt (lst :int list) (x: int) (y:int): int =
if [List.hd(lst)] = [] then y
else
match [List.hd(lst)] with
| [] → y
| [x] → countDupInt (List.tl(lst)) x (y + 1)
| _ :: t-> countDupInt t x y
;;

List.hd(lst) will always return a exception failure when the the list is empty and since the base case is the empty list, can not figure out a way around it. Any help would be great

You probably want to match directly on the list:

let rec count_dup_int ls x y =
  match ls with
  | [] -> ...
  | head :: tail -> ...
2 Likes

Thank you Gopiandcode i am over thinking the problems. I appreciate it.

actually can you elaborate a little more
i need to match against x then return y when finished

Check out this page 3.5. Pattern Matching with Lists · GitBook

Your final match will probably look something like this:

let rec count_dup_int ls x y =
  match ls with 
  | [] -> ...
  | head :: tail when head = x -> ...
  | _ :: tail -> ...
1 Like