[erlang-questions] join/2 function

Torbjorn Tornkvist tobbe@REDACTED
Mon Dec 18 09:34:07 CET 2006


This was discussed recently on the #erlang channel.
My take on this was:


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


See the attached file for all three versions.

3> 
timer:tc(implode,t1,[["abc","def","ghi","jkl","mno","pqr","stu","vxyz","123456789","987654321"], 
"."]).
{7,"abc.def.ghi.jkl.mno.pqr.stu.vxyz.123456789.987654321"}
4> 
timer:tc(implode,t1,[["abc","def","ghi","jkl","mno","pqr","stu","vxyz","123456789","987654321"], 
"."]).
{7,"abc.def.ghi.jkl.mno.pqr.stu.vxyz.123456789.987654321"}
5> 
timer:tc(implode,t2,[["abc","def","ghi","jkl","mno","pqr","stu","vxyz","123456789","987654321"], 
"."]).
{10,"abc.def.ghi.jkl.mno.pqr.stu.vxyz.123456789.987654321"}
6> 
timer:tc(implode,t2,[["abc","def","ghi","jkl","mno","pqr","stu","vxyz","123456789","987654321"], 
"."]).
{10,"abc.def.ghi.jkl.mno.pqr.stu.vxyz.123456789.987654321"}
7> 
timer:tc(implode,t3,[["abc","def","ghi","jkl","mno","pqr","stu","vxyz","123456789","987654321"], 
"."]).
{5,"abc.def.ghi.jkl.mno.pqr.stu.vxyz.123456789.987654321"}
8> 
timer:tc(implode,t3,[["abc","def","ghi","jkl","mno","pqr","stu","vxyz","123456789","987654321"], 
"."]).
{5,"abc.def.ghi.jkl.mno.pqr.stu.vxyz.123456789.987654321"}


--Tobbe


Matthias Lang wrote:
> Hoan Ton-That writes:
> 
>  > I think that the following function join should
>  > be included in the lists module.
>  > 
>  > join(Sep, List) ->
>  >   lists:foldl(fun(A, "") -> A; (A, Acc) -> Acc ++ Sep ++ A end, "", List).
> 
> Your implementation of join is quadratic in the length of the list.
> 
> Here's one O(N) way to do it:
> 
>   lcjoin(Sep, [H|T]) ->
>       Joined = [ [Sep|X] || X <- T ],
>       lists:flatten([H|Joined]).
> 
> In many cases the lists:flatten/1 call is unnecessary.
> 
> Matthias

-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: implode.erl
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20061218/9216878d/attachment.ksh>


More information about the erlang-questions mailing list