Issue
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)
.
Answered By - Thomash
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.