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"]}
].
There is a nice solution to this one by using the sofs
module in the Erlang Standard library. The sofs
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.
-module(z).
-compile(export_all). % Don't do this normally :)
x() ->
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, [10, 90]},{k2, [20, 210]},{k3, [30, 60]},{k4, [20.9, 66.9]},{k6, ["Hello universe", "Hello world"]}],
R = sofs:relation(L1 ++ L2),
F = sofs:relation_to_family(R),
L3 = sofs:to_external(F),
ok.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With