Is Erlang's ++
operator simply syntactic sugar for lists:concat
or is it a different operation altogether? I've tried searching this, but it's impossible to Google for "++" and get anything useful.
This is how the lists:concat/1
is implemented in the stdlib/lists module:
concat(List) ->
flatmap(fun thing_to_list/1, List).
Where:
flatmap(F, [Hd|Tail]) ->
F(Hd) ++ flatmap(F, Tail);
flatmap(F, []) when is_function(F, 1) -> [].
and:
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
So, lists:concat/1
actually uses the '++' operator.
X ++ Y
is in fact syntactic sugar for lists:append(X, Y)
.
http://www.erlang.org/doc/man/lists.html#append-2
The function lists:concat/2 is a different beast. The documentation describes it as follows: "Concatenates the text representation of the elements of Things. The elements of Things can be atoms, integers, floats or strings."
One important use of ++
has not been mentioned yet: In pattern matching. For example:
handle_url(URL = "http://" ++ _) ->
http_handler(URL);
handle_url(URL = "ftp://" ++ _) ->
ftp_handler(URL).
It's an entirely different operation. ++ is ordinary list appending. lists:concat takes a single argument (which must be a list), stringifies its elements, and concatenates the strings.
++ : http://www.erlang.org/doc/reference_manual/expressions.html
lists:concat : http://www.erlang.org/doc/man/lists.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With