[erlang-questions] list:join() for erlang?

ok ok@REDACTED
Fri Sep 14 04:14:06 CEST 2007


On 14 Sep 2007, at 8:38 am, Bob Ippolito wrote:
> Using ++ all over the place is probably a bad idea, at least according
> to the performance guide and my intuition. I haven't profiled it.

I believe you have misunderstood the performance guide.
When you want to concatenate lists, ++ is the tool for the job.

>
> This is our join/2, which is largely the same but uses lists:flatten/1
> instead of ++:

But that changes the semantics.  It will accept stuff that I did not
at all wish my code to accept.

> join([S], _Separator) ->
>     lists:flatten(S);

This does *more* copying than the ++ version.

If you are happy with using flatten/1 (as I am not), then a much
simpler approach is

join([], _) -> [];
join([List|Lists], Separator) ->
     lists:flatten([List | [[Separator,Next] || Next <- Lists]]).

This turns [S1,S2,S3,S4]
      into  [S1,[Sep,S2],[Sep,S3],[Sep,S4]]
and then flattens that.





More information about the erlang-questions mailing list