Search code examples
erlang

Combine/Merge Two Erlang lists


How to combine tuple lists in erlang? I have lists:

L1 = [{k1, 10}, {k2, 20}, {k3, 30}, {k4, 20.9}, {k6, "Hello world"}],

and

L2 = [{k1, 90}, {k2, 210}, {k3, 60}, {k4, 66.9}, {k6, "Hello universe"}],

now I want a combined list as :

L3 = [
       {k1, [10, 90]},
       {k2, [20, 210]},
       {K3, [30, 60]},
       {k4, [20.9, 66.9]},
       {K6, ["Hello world", "Hello universe"]}
     ].

Solution

  • Something shorter, and the lists don't even have to posses the same keys, and can be unordered:

    merge(In1,In2) ->
        Combined = In1 ++ In2,
        Fun      = fun(Key) -> {Key,proplists:get_all_values(Key,Combined)} end,
        lists:map(Fun,proplists:get_keys(Combined)).
    

    Fun could be written directly in the lists:map/2 function, but this makes it readable.

    Output, with data from example:

    1> test:merge(L1,L2).
    [{k1,"\nZ"},
     {k2,[20,210]},
     {k3,[30,60]},
     {k4,[20.9,66.9]},
     {k6,["Hello world","Hello universe"]}]
    

    "\nZ" is because erlang interprets [10,90] as a string (which are, in fact, lists). Don't bother.