String concatenation
February 25th, 2009
As we all know, Erlang treats String as the array of integers, hence operations on list are applicable on String.
String concatenation can be done in different ways in Erlang
1> X="I love ". "I love " 2> Y="Erlang". "Erlang" 3> string:concat(X, Y). "I love Erlang" 4> string:join([X, Y], ""). "I love Erlang" 5> X ++ Y. "I love Erlang" 6> lists:append(X, Y). "I love Erlang" 7> lists:concat([X, Y]). "I love Erlang"
You could also do X ++ Y, I’m not sure if it’s just syntactic sugar for lists:concat(…) or not but I suspect it might be.
Ops, I’m blind. Seems you already have an example of ++.
Thanks, Fabian.
I’ve looked at the source code for lists.erl, your’re right, lists:concat/1 uses ++ for concatenation:
concat(List) ->
flatmap(fun thing_to_list/1, List).
thing_to_list(X) when is_integer(X) -> integer_to_list(X);
thing_to_list(X) when is_float(X) -> float_to_list(X);
thing_to_list(X) when is_atom(X) -> atom_to_list(X);
thing_to_list(X) when is_list(X) -> X. %Assumed to be a string
flatmap(F, [Hd|Tail]) ->
F(Hd) ++ flatmap(F, Tail);
Hi Trung,
According to Programming Erlang, the source for the lists module is only an illustrative implementation. Use of ++ is discouraged for all but trivially small lists.
-Denny
Thanks Denny for the comment.
Hmm, I though initially that ++ is quite native, why they used it in lists:concat/1 implementation then?
@Denny Abraham
I was also confused about “++” vs. “lists:concat”, then I write a simple test, it seems “lists:concat” was obviously faster. I think Denny is right, the BIFs may not be implemented in Erlang indeed.
The “string:concat/2” seems not very useful compared to “lists:concat/1”, since it only takes two arguments.
Hope the author will make a comparison to these functions 😉