Erlang list manipulation

I have a list of tuples:

L = [{1, [a, b, c]}, {2, [d, e, f]}, {3, [[h, i, j], [k, l, m]]}]

this is what i have

lists:map(fun({_, B}-> B end, L).

output

[[a, b, c], [d, e, f], [[h, i, j], [k, l, m]]]

I want:

[[a, b, c], [d, e, f], [h, i, j], [k, l, m]]

seems like a pretty simple problem, but I can't figure out how to do this. Please, help!

+3
source share
3 answers

We will see...

1> L = [{1, [a, b, c]}, {2, [d, e, f]}, {3, [[h, i, j], [k, l, m]]}].
[{1,[a,b,c]},{2,[d,e,f]},{3,[[h,i,j],[k,l,m]]}]

Trivial and simple, but not tail recursive:

2> lists:foldr(fun ({_,[X|_]=E},A) when is_list(X) -> lists:append(A,E);
                   ({_,E},A) -> [E|A] end,
                [], L).
[[a,b,c],[d,e,f],[h,i,j],[k,l,m]]

Not tail-recursive not very nice, but ...

3> lists:reverse(lists:foldl(fun ({_,[X|_]=E},A) when is_list(X) ->
                                     lists:reverse(E,A);
                                 ({_,E},A) -> [E|A] end,
                             [], L)).
[[a,b,c],[d,e,f],[h,i,j],[k,l,m]]

... also has a tail-recursive version (thanks to Zed for pointing out lists:reverse/2).

+5
source

In your specific example example, you can define the following function:

group3([], Acc) ->
     Acc;
group3([A,B,C|Tl], Acc) ->
    group3(Tl, [[A,B,C]] ++ Acc).

group3(L) ->
    lists:reverse(group3(L, [])).

and call it like this:

group3(lists:flatten(lists:map(fun({_, B}) -> B end, L))).

Hope this is enough to give you an overall strategy.

+2
source
-module(z).
-export([do/1]).

do([{_,[X|_] = L}|Tl]) when is_list(X) -> L ++ do(Tl);
do([{_, L}       |Tl])                 -> [L|do(Tl)];
do([])                                 -> [].

test:

1> z:do(L).
[[a,b,c],[d,e,f],[h,i,j],[k,l,m]]
+1
source

Source: https://habr.com/ru/post/1721641/


All Articles