我如何解决 Ocaml 中的字典问题?
How could I solve this Dictionary problem in Ocaml?
根据给定的元组列表 [("x", 3); ("num", 17); ("y", 7); ("x", 5)]
创建一个字典,如果有相同的键,则对它们的值求和。所以在这个例子中,应该创建一个这样的字典
[("x", 8); ("num", 17); ("y", 7)];
字典中的顺序无关紧要。
这是我试过的代码:
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;;
但它不断覆盖相同键的值(输出为[("num", 17); ("x", 5); ("y", 7)]
)
您正在寻找地图的 update
函数,而不是 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)]
使用此版本,MS.bindings f1
将 return [("num", 17); ("x", 8); ("y", 7)]
。
根据给定的元组列表 [("x", 3); ("num", 17); ("y", 7); ("x", 5)]
创建一个字典,如果有相同的键,则对它们的值求和。所以在这个例子中,应该创建一个这样的字典
[("x", 8); ("num", 17); ("y", 7)];
字典中的顺序无关紧要。
这是我试过的代码:
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;;
但它不断覆盖相同键的值(输出为[("num", 17); ("x", 5); ("y", 7)]
)
您正在寻找地图的 update
函数,而不是 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)]
使用此版本,MS.bindings f1
将 return [("num", 17); ("x", 8); ("y", 7)]
。