如果我有一个成对的列表。 (String, int) 如何将字符串中的每个 int 添加到一对相同

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

我有一个问题,我有一个字符串 int 对列表,我想用相同的 String ex 对 int 的总数求和: 列表 -> [("a",1);("b",1);("a",1);("c",1)] 应该 return list -> [("a",2);("b",1);("c",1)] order doesn't mather will sort later'

现在我有这个

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    
;;

这就是我的想法,但我知道它还行不通

ps 我不能使用 ocaml 支持的命令式内容

如果您假设您的列表已排序,"something i cant think of yet" 只是复制列表的头部并将函数递归地应用于尾部:(c1,n1)::merge ((c2,n2)::xs).