eclipseocaml

If i have a list of pairs ex. (String, int) how to add every int in strings are the same to one single pair


i have this problem where i have a list of pairs string int and i want to sum the total of ints with the same String ex: list -> [("a",1);("b",1);("a",1);("c",1)] should return list -> [("a",2);("b",1);("c",1)] order doesnt mather will sort later´

for now i have this

let rec merge l = 
  match l with
  | [] -> []
  | (c1,n1)::(c2,n2)::xs -> 
    if c1 = c2 then
      (c1, n1+n2)::merge xs
    else
      something i cant think of yet

thats my train on thougth but i know it wont work yet

ps i cant use imperative stuff suported by ocaml


Solution

  • If you assume that your list is sorted, the "something i cant think of yet" is simply copying the head of the list and applying the function recursively to the tail: (c1,n1)::merge ((c2,n2)::xs).