[erlang-questions] Which is best? string:concat or ++?
Richard O'Keefe
ok@REDACTED
Tue May 8 00:45:55 CEST 2012
On 8/05/2012, at 3:39 AM, Paul Barry wrote:
>
> http://dev.af83.com/2012/01/16/erlang-iolist.html
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
strings.
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(NS) ->
reify_nstring(NS, []).
reify_nstring([A|B], S) ->
reify_nstring(A, reify_nstring(B, S));
reify_nstring([], S) ->
S;
reify_nstring(C, S) when is_integer(C), C >= 0 ->
[C|S].
% Perform F(C) for each character C in nstring S.
foreach_nstring(F, [A|B]) ->
foreach_nstring(F, A),
foreach_nstring(F, B);
foreach_nstring(F, []) ->
ok;
foreach_nstring(F, C) when is_integer(C), C >= 0 ->
F(C).
% Report the effective length of an nstring in codepoints.
length_nstring(S) ->
length_nstring(S, 0).
length_nstring([A|B], N) ->
length_nstring(B, length_nstring(A, N));
length_nstring([], N) ->
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
mailing list