[erlang-questions] Which is best? string:concat or ++?
Tue May 8 00:45:55 CEST 2012
On 8/05/2012, at 3:39 AM, Paul Barry wrote:
Under the heading IOList, the third paragraph gets list
concatenation about as wrong as it possibly can.
(The last sentence of that paragraph is right, though.)
Let's consider a simple "nested list" representation of
nstring = integer |  | [nstring|nstring]
integer represents a codepoint
 represents an empty string
[A|B] represents (but is not) the concatenation of A and B
% Convert an nstring to a plain string.
% Do not allocate any space that is not part of the
% final result.
reify_nstring([A|B], S) ->
reify_nstring(A, reify_nstring(B, S));
reify_nstring(, S) ->
reify_nstring(C, S) when is_integer(C), C >= 0 ->
% Perform F(C) for each character C in nstring S.
foreach_nstring(F, [A|B]) ->
foreach_nstring(F, ) ->
foreach_nstring(F, C) when is_integer(C), C >= 0 ->
% Report the effective length of an nstring in codepoints.
length_nstring([A|B], N) ->
length_nstring(B, length_nstring(A, N));
length_nstring(, N) ->
length_nstring(C, N) when is_integer(C), C >= 0 ->
N + 1.
You can generalise this to allow atoms and binaries
as well as character codes.
The basic idea is to *describe* concatenation without
*doing* it, and to give you functions that act *as if*
the concatenation had been done.
More information about the erlang-questions