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}
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
2条答案
按热度按时间7gcisfzg1#
There's no builtin function in Erlang that does exactly this but it can be done with
maps:fold/3
andmaps:update_with/4
like this: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
niwlg2el2#
这个函数将合并两个Map,运行一个函数(Fun),其中键存在于两个Map中。它还处理了Map1大于Map2的情况,反之亦然。
erl shell中的示例用法: