Is there an optimized way to zip 3 lists, in order
zip(L1, L2, L3)
So that they result in a list of tuples, example:
L1 = [1, 2, 3, 4],
L2 = [a, b, c, d],
L3 = [1, 2, 3, 4],
Resultant List of Tuples Should look like:
[{1,a,1}, {2,b,2}, {3,c,3}, {4,d,4}]
It seems you need to use lists:zip3/3:
1> L1 = [1, 2, 3, 4].
[1,2,3,4]
2> L2 = [a, b, c, d].
[a,b,c,d]
3> L3 = [1, 2, 3, 4].
[1,2,3,4]
4> lists:zip3(L1, L2, L3).
[{1,a,1},{2,b,2},{3,c,3},{4,d,4}]
1> lists:zip3([1,2,3,4],[a,b,c,d],[1,2,3,4]).
[{1,a,1},{2,b,2},{3,c,3},{4,d,4}]
2>
Or you could implement it manually:
myzip3([], _, _) ->
[];
myzip3([X|Xs], [Y|Ys], [Z|Zs]) ->
[{X,Y,Z}|myzip3(Xs,Ys,Zs)].
Or using accumulator:
myzip3acc(Xs, Ys, Zs) ->
myzip3acc_do([], Xs, Ys, Zs).
myzip3acc_do(Acc, [], _, _) ->
lists:reverse(Acc);
myzip3acc_do(Acc, [X|Xs], [Y|Ys], [Z|Zs]) ->
myzip3acc_do([{X,Y,Z}|Acc], Xs,Ys,Zs).
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