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
source
share