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"]}
].
What happened to
lists:zipwith/2
?Assumptions:
lists:zipwith(fun({X, Y}, {X, Z}) -> {X, [Y, Z]} end, L1, L2).
Something shorter, and the lists don't even have to posses the same keys, and can be unordered:
Fun could be written directly in the
lists:map/2
function, but this makes it readable.Output, with data from example:
"\nZ"
is because erlang interprets [10,90] as a string (which are, in fact, lists). Don't bother.This technique is called merge join. It is well known in database design.
If there can be different sets of keys in both lists and you are willing to drop those values you can use
Or if you would like store those values in lists
You can of course use tail recursive version if you don't mind result in reverse order or you can always use
lists:reverse/1
Or
Or
If there is possibility that one of lists can contain same keys and you are willing collect all values you can consider this
Maybe this is not the best way, but it does what you are trying to achieve.
Edit I'm assuming that the input lists are ordered as in your sample input. If not you can use
lists:sort/2
to sort them before merging.There is a nice solution to this one by using the
sofs
module in the Erlang Standard library. Thesofs
module describes a DSL for working with mathematical sets. This is one of those situations, where you can utilize it by transforming your data into the SOFS-world, manipulate them inside that world, and then transform them back again outside afterwards.Note that I did change your L3 a bit, since
sofs
does not preserve the string order.