DvdiidI
DvdiidI

Reputation: 73

How could I solve this Dictionary problem in Ocaml?

Being given the list of tuples [("x", 3); ("num", 17); ("y", 7); ("x", 5)] create a dictionary in which if there are equal keys their values are summed. So on this example, a dictionary like this should be created [("x", 8); ("num", 17); ("y", 7)]; it doesn't matter the order in dictionary.

This is the code I tried:

module MS = Map.Make(String);;
let f l = List.fold_left (fun acc (key, value) -> MS.add key value acc) MS.empty l;;
let f1 = f [("x", 3); ("num", 17); ("y", 7); ("x", 5)];;
MS.bindings f1;;

But it keeps overwriting the value of the same keys(the output is [("num", 17); ("x", 5); ("y", 7)])

Upvotes: 0

Views: 166

Answers (1)

Shawn
Shawn

Reputation: 52529

You're looking for Map's update function, not add:

module MS = Map.Make(String)

let f l =
  List.fold_left
    (fun acc (key, value) ->
         MS.update key (function Some v -> Some (value + v) | None -> Some value) acc)
     MS.empty l

let f1 = f [("x", 3); ("num", 17); ("y", 7); ("x", 5)]

With this version, MS.bindings f1 will return [("num", 17); ("x", 8); ("y", 7)].

Upvotes: 1

Related Questions