我将对这两个列表进行排序,然后与一个简单的函数合并。我目前还没有更快的方法来做到这一点。
test() ->
L1 = [{k1, 1}, {k2, 2}, {k32, 32}],
L2 = [{k32, 0.1}, {k2, 0.2}, {k1, 0.32}],
MergeFun = fun(X, Y) -> X+Y end,
merge(MergeFun, L1, L2).
merge(Fun, L1, L2) ->
my_marge(Fun, lists:keysort(1, L1), lists:keysort(1, L2), []).
my_marge(Fun, [{Key, V1} | L1], [{Key, V2} | L2], Acc) ->
my_marge(Fun, L1, L2, [{Key, Fun(V1, V2)} | Acc]);
my_marge(Fun, [], [{Key, V} | L], Acc) ->
my_marge(Fun, [], L, [{Key, V} | Acc]);
my_marge(Fun, [{Key, V} | L], [], Acc) ->
my_marge(Fun,L,[], [{Key, V} | Acc]);
my_marge(Fun, [{Key1, V1} | L1], [{Key2, V2} | L2], Acc) when Key1 < Key2 ->
my_marge(Fun, L1, [{Key2, V2} | L2], [{Key1, V1} | Acc]);
my_marge(Fun, L1, [{Key, V} | L2], Acc) ->
my_marge(Fun, L1, L2, [{Key, V} | Acc]);
my_marge(_Fun, [], [], Acc) ->
Acc.