Erlang -合并Map

6vl6ewon  于 2022-12-08  发布在  Erlang
关注(0)|答案(2)|浏览(138)

I am trying to figure out how to merge two maps in a way that allows me to process elements with the same keys.
For example, merging
#{"Ala" => 1,"kota" => 3}
with
#{"kota" => 4}
should result in:
#{"Ala" => 1,"kota" => 7}

7gcisfzg

7gcisfzg1#

There's no builtin function in Erlang that does exactly this but it can be done with maps:fold/3 and maps:update_with/4 like this:

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}

The code basically does this: for each item in B, if the same key exists in A, it gets the value (V) and adds the current value(X). If it doesn't exist, it sets the value to V

niwlg2el

niwlg2el2#

这个函数将合并两个Map,运行一个函数(Fun),其中键存在于两个Map中。它还处理了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}

相关问题