Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine/Merge Two Erlang lists

Tags:

erlang

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"]}
     ].
like image 369
Laxmikant Ratnaparkhi Avatar asked Feb 19 '14 07:02

Laxmikant Ratnaparkhi


1 Answers

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.
like image 181
I GIVE CRAP ANSWERS Avatar answered Sep 21 '22 15:09

I GIVE CRAP ANSWERS