Erlang - 合并地图

时间:2017-10-12 16:46:18

标签: erlang maps

我试图找出如何以允许我使用相同键处理元素的方式合并两个maps

例如,合并

#{"Ala" => 1,"kota" => 3}

#{"kota" => 4}

应该导致:

#{"Ala" => 1,"kota" => 7}

2 个答案:

答案 0 :(得分:7)

Erlang中没有内置函数可以完成此操作,但可以使用function gatherDates(db) { const dates = []; let today = getToday(); dates.push(today); let dateQuery = "SELECT date FROM event_dates"; return new Promise((resolve) => { db.query(dateQuery, (err, newDates) => { for(let row of newDates) { dates.push(row.date); } resolve(dates); }); }); } maps:fold/3完成此操作:

maps:update_with/4

代码基本上这样做:对于B中的每个项目,如果A中存在相同的密钥,则获取值(V)并添加当前值(X)。如果它不存在,则将值设置为1> A = #{"Ala" => 1,"kota" => 3}. #{"Ala" => 1,"kota" => 3} 2> B = #{"kota" => 4}. #{"kota" => 4} 3> maps:fold(fun(K, V, Map) -> maps:update_with(K, fun(X) -> X + V end, V, Map) end, A, B). #{"Ala" => 1,"kota" => 7}

答案 1 :(得分:0)

此函数将合并两个地图,并运行一个函数(Fun),其中两个地图中都存在键。它还处理了Map1大于Map2的情况,反之亦然。

map_merge(Map1, Map2, Fun) ->
    Size1 = maps:size(Map1),
    Size2 = maps:size(Map2),
    if
        Size1 > Size2 ->
            Folder = fun(K, V1, Map) ->
                maps:update_with(K, fun(V2) -> Fun(K, V1, V2) end, V1, Map)
            end,
            maps:fold(Folder, Map1, Map2);
        true ->
            Folder = fun(K, V1, Map) ->
                maps:update_with(K, fun(V2) -> Fun(K, V2, V1) end, V1, Map)
            end,
            maps:fold(Folder, Map2, Map1)
    end.

在erl shell中的用法示例:

1> my_module:map_merge(#{"a" => 10, "b" => 2}, #{"a" => 1}, fun(K, V1, V2) -> V1 + V2 end).
#{"a" => 11,"b" => 2}
2> my_module:map_merge(#{"a" => 10}, #{"a" => 1, "b" => 2}, fun(K, V1, V2) -> V1 + V2 end).
#{"a" => 11,"b" => 2}
3> my_module:map_merge(#{"a" => 10},#{"a" => 10}, fun(K, V1, V2) -> V1 + V2 end).
#{"a" => 20}