Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang ++ operator. Syntactic sugar, or separate operation?

Tags:

erlang

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.

like image 311
Travis Webb Avatar asked Mar 17 '11 12:03

Travis Webb


4 Answers

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.

like image 104
Roberto Aloi Avatar answered Dec 29 '22 02:12

Roberto Aloi


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."

like image 34
RichardC Avatar answered Dec 29 '22 02:12

RichardC


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).
like image 27
ndim Avatar answered Dec 29 '22 04:12

ndim


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

like image 26
Gareth McCaughan Avatar answered Dec 29 '22 04:12

Gareth McCaughan