[erlang-questions] join/2 function

Matthias Lang matthias@REDACTED
Sun Dec 17 09:39:36 CET 2006


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



More information about the erlang-questions mailing list