You can use lists:foldl
to apply merge
to a list of lists. Here is an example:
-module(test).
-export([test/0]).
merge(L1, L2) ->
merge_(lists:sort(L1), lists:sort(L2)).
merge_([{K, V1}|T1], [{K, V2}|T2]) when is_list(V1), is_list(V2)
-> [{K, V1 ++ V2}|merge_(T1, T2)];
merge_([{K, V1}|T1], [{K, V2}|T2]) when is_list(V1)
-> [{K, V1 ++ [V2]}|merge_(T1, T2)];
merge_([{K, V1}|T1], [{K, V2}|T2]) when is_list(V2)
-> [{K, [V1] ++ V2}|merge_(T1, T2)];
merge_([{K, V1}|T1], [{K, V2}|T2])
-> [{K, [V1, V2]}|merge_(T1, T2)];
merge_([{K1, V1}|T1], [{K2, _}|_]=L2) when K1 < K2
-> [{K1, [V1]}|merge_(T1, L2)];
merge_(L1, [{K2, V2}|T2]) when is_list(V2)
-> [{K2, V2}|merge_(L1, T2)];
merge_(L1, [{K2, V2}|T2])
-> [{K2, [V2]}|merge_(L1, T2)];
merge_(L1, []) -> [{K, V} || {K, V} <- L1].
test() ->
L1 = [{k1, 10}, {k2, 20}, {k3, 30}, {k4, 20.9}, {k6, "Hello world"}],
L2 = [{k1, 90}, {k2, 210}, {k3, 60}, {k4, 66.9}, {k6, "Hello universe"}],
L3 = [{k1, 45}, {k2, 35}, {k3, 37}, {k4, 77.9}, {k6, "Hello cosmo"}],
lists:foldl(fun merge/2, [], [L1, L2, L3]).
And here is the outcome:
36> test:test().
[{k1,"-Z\n"},
{k2,[35,210,20]},
{k3,[37,60,30]},
{k4,[77.9,66.9,20.9]},
{k6,"Hello cosmoHello universeHello world"}]
As you can see,
You need to modify the merge
function to handle list (not just atom as in your original question). It is already done in my example code, which is based on Vychodil's answer.
You need to modify the merge
function to handle string properly (as evidence in keys k1 and k6). You should be able to fix it yourself.
Last but not least, you should accept an answer when it resolves your question. Check this link for why.