-module(implode).
-compile(export_all).

t1(List, Sep) ->
    lists:foldl(fun(A, "") -> A; (A, Acc) -> Acc ++ Sep ++ A end, "", List).

t2([H|T], Sep) ->
    Joined = [ [Sep|X] || X <- T ],
    lists:flatten([H|Joined]).

t3(List, Sep) ->
    lists:foldr(fun(X,[]) -> X; (X,Acc) -> X++Sep++Acc end, "", List).

t4([H|T], Sep) ->
    H ++ lists:concat([Sep ++ X || X <- T]).

t5([H|T], Sep) -> H ++ t6(T, Sep).
t6([], _)      -> [];
t6([H|T], Sep) -> Sep ++ H ++ t6(T, Sep).

do1(N, L,S) when N > 0 ->
    t1(L,S),
    do1(N-1,L,S);
do1(_,_,_) ->
    erlang:garbage_collect(),
    ok.

do2(N, L,S) when N > 0 ->
    t2(L,S),
    do2(N-1,L,S);
do2(_,_,_) ->
    erlang:garbage_collect(),
    ok.

do3(N, L,S) when N > 0 ->
    t3(L,S),
    do3(N-1,L,S);
do3(_,_,_) ->
    erlang:garbage_collect(),
    ok.

do4(N, L,S) when N > 0 ->
    t4(L,S),
    do4(N-1,L,S);
do4(_,_,_) ->
    erlang:garbage_collect(),
    ok.

do5(N, L,S) when N > 0 ->
    t5(L,S),
    do5(N-1,L,S);
do5(_,_,_) ->
    erlang:garbage_collect(),
    ok.

l1() ->
    ["abc","def","ghi","jkl","mno","pqr","stu","vxyz","123456789","987654321"].

l2() ->
    lists:duplicate(50,lists:duplicate(50,$a)).

test(N, L) ->
    S = ".",
    Tests = [do1, do2, do3, do4, do5],
    Times = lists:map(fun(F) -> {T, _} = timer:tc(?MODULE, F, [N,L,S]), T end, Tests),
    lists:foldl(fun(T, I) -> io:format("do~w(~w,L,~p): ~7wus\n", [I, N, S, T]), I+1 end,
                1, Times),
    ok.
