[erlang-questions] Merging maps with a fun like dict:merge/3

Ivan Uemlianin ivan@REDACTED
Sun Aug 23 19:05:40 CEST 2015


Dear All

The maps module does not have a merge/3 like dict:merge/3, which calls a 
function fun(Key, Val1, Val2) when both dicts have the same key.  From 
the documentation, "If a key occurs in both dictionaries then Fun is 
called with the key and both values to return a new value."

The dict documentation says that dict:merge/3 is faster than an 
equivalent implemented in erlang.

http://www.erlang.org/doc/man/dict.html#merge-3

Why does the maps module not have a similar merge/3?  Is it because 
writing our own erlang implementation is at fast as it gets?

Below is an implementation which seems to work.  Can it be made faster?


merge_maps(Fun, M1, M2) ->
     maps:fold(fun(K, V1, Acc) ->
                       case maps:is_key(K, Acc) of
                           false ->
                               maps:put(K, V1, Acc);
                           true ->
                               V2 = maps:get(K, Acc),
                               maps:put(K, Fun(K, V1, V2), Acc)
                       end
               end,
               M1,
               M2).

merge_maps_test() ->
     merge_maps(fun(_K, V1, V2) -> V1 + V2 end,
                #{a => 1, b => 2, c => 3},
                #{b => 2, c => 3, d => 4}) =:=
         #{a => 1, b => 4, c => 6, d => 4}.


With thanks and best wishes

Ivan

-- 
============================================================
Ivan A. Uemlianin PhD
Llaisdy
Speech Technology Research and Development

                     ivan@REDACTED
                         @llaisdy
                          llaisdy.wordpress.com
               github.com/llaisdy
                      www.linkedin.com/in/ivanuemlianin

                         festina lente
============================================================




More information about the erlang-questions mailing list