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

Paulo Sérgio Almeida psa@REDACTED
Fri Sep 14 12:39:44 CEST 2007


Bjorn Gustavsson wrote:

> The Efficiency Guide could be a little bit clearer about '++'. We will probably
> update it in the R12B release.
> 
> '++' is not always bad. It is bad if you build a result on the left-hand side of '++',
> because the result that is growing will be copied again and again. It is fine if the
> result is on the right-hand side, because the right-hand side is not copied.
> 
> /Bjorn

This insight is important for people to start using ++ more frequently.

Regarding list reverse, while playing around and observing:

85> erlang:is_builtin(lists, reverse, 1).
false

I found out that what is builtin is another function, reverse/2, which 
is not much advertised, but that may be very useful, as the fastest way 
to simultaneously reverse a list and concatenate to another.

87> lists:reverse("345", "21").
"54321"

A list:join version exploring this reverse/2 is not much slower than the 
version with ++.

join([], _Sep) -> [];
join([H|T], Sep) -> join(T, Sep, lists:reverse(H)).

join([], _Sep, Ac) -> lists:reverse(Ac);
join([H | T], Sep, Ac) ->
   join(T, Sep, lists:reverse(H,lists:reverse(Sep,Ac))).

In other cases where we truly want to reverse and concatenate it will be 
quite an amazing function to have around that deserves more advertising.

Regards,
Paulo







More information about the erlang-questions mailing list