BAR
BAR

Reputation: 17171

Erlang lists:zip3 .. but more than 3

So we can use this function in erlang

DataList = lists:zip3(Data1, Data2, Data3)

to generate:

Eshell V5.9  (abort with ^G)
1> Data1 = ["aaa","bbb","ccc"].
["aaa","bbb","ccc"]
2> Data2 = ["aaa2","bbb2","ccc2"].
["aaa2","bbb2","ccc2"]
3> Data3 = ["aaa3","bbb3","ccc3"].
["aaa3","bbb3","ccc3"]
4> DataList = lists:zip3(Data1, Data2, Data3).                                   
[{"aaa","aaa2","aaa3"},
 {"bbb","bbb2","bbb3"},
 {"ccc","ccc2","ccc3"}]

I need something that can do this automatically:

DataList = lists:zipN(Data1, Data2, Data3, ... Data N)

Upvotes: 1

Views: 371

Answers (2)

danechkin
danechkin

Reputation: 1306

write your own zipN function like this:

zipN([]) ->
    [];
zipN(ListOfLists) ->
    zipN([], ListOfLists, [], []).

zipN(Ts, [], E, Acc) ->
    zipN([], lists:reverse(Ts), [], [list_to_tuple(lists:reverse(E)) | Acc]);

zipN(Ts, [[Head | Tail] | ListOfLists], E, Acc) ->
    zipN([Tail | Ts], ListOfLists, [Head | E], Acc);

zipN([], _, [], Acc) ->
    lists:reverse(Acc).

Upvotes: 3

Alexey Romanov
Alexey Romanov

Reputation: 170919

You can't do literally this (except by using parse_transform), because Erlang functions can't have variable number of arguments. Your function would have to accept a list of lists:

DataList = lists:zipN([Data1, Data2, Data3, ... DataN])

This can be done by transposing the list and then converting every element of the result to a tuple.

Upvotes: 1

Related Questions