Best way to convert a flat list to a set of two tuples in Erlang?

Is there a quick way to convert a flat list to a list of two tuples so that a flat list such as [1,2,3,4,5,6] becomes [{1,2}, {3,4}, {5,6 }]?

This works, but it feels just WRONG:

tuples_from_flat_list(Target) ->
    TargetWithIndex = lists:zip(lists:seq(1, length(Target)), Target),
    {K, V} = lists:partition(fun({I, _}) -> I rem 2 == 1 end, TargetWithIndex),
    lists:zipwith(fun({_, X}, {_, Y}) -> {X, Y} end, K, V).
+5
source share
3 answers

The shortest and most concise approach:

pair_up([A, B | Tail]) ->
    [{A,B} | pair_up(Tail)];
pair_up([]) ->
    [].

Or a longer version with a battery, but still very idiomatic Erlang:

pair_up(List) ->
    pair_up(List, []).

pair_up([A, B | Tail], Acc) ->
    pair_up(Tail, [{A,B} | Acc]);
pair_up([], Acc) ->
    lists:reverse(Acc).

See this section in the Erlang Performance Guide, "Myth: Recursive Tail Functions Much Faster Than Recursive Functions . "

, "badarg" . , .

":" ++ " " , , , , .

+10
tuples_from_flat_list(List) -> tuples_from_flat_list(List, []).

tuples_from_flat_list([], Result) -> lists:reverse(Result).
tuples_from_flat_list([X, Y|T], Acc) -> tuples_from_flat_list(T, [{X, Y}|Acc]).

.

+3

This version is more efficient than the "direct" approach with the list of concatenations proposed earlier:

combine(L) when length(L) rem 2 == 0 -> combine([], L).
combine(Acc, []) -> lists:reverse(Acc);
combine(Acc, [H1,H2|T])  -> combine([{H1, H2}|Acc], T).

For comparison:

combine.erl

-module(combine).
-export([reverse/1, straight/1, test/2]).

test(F, L) -> {Micros, _} = timer:tc(?MODULE, F, [L]), Micros.

reverse(L) when length(L) rem 2 == 0 -> reverse([], L).                                  
straight(L) when length(L) rem 2 == 0 -> straight([], L).

reverse(Acc, []) -> lists:reverse(Acc);
reverse(Acc, [H1, H2 | T]) -> reverse([{H1, H2} | Acc], T).

straight(Acc, []) -> Acc;
straight(Acc, [H1, H2 | T]) -> straight(Acc ++ [{H1, H2}], T).

exit:

130> combine:test(reverse, lists:seq(1,1000)).
34
131> combine:test(straight, lists:seq(1,1000)).
1772
+2
source

All Articles