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

岁酱吖の 提交于 2019-12-08 18:23:55

问题


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.


回答1:


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.




回答2:


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




回答3:


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



回答4:


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




回答5:


Most list functions actually uses the '++' operator: for example the list:append/2:

The source code defines it as follows:

-spec append(List1, List2) -> List3 when
      List1 :: [T],
      List2 :: [T],
      List3 :: [T],
      T :: term().

append(L1, L2) -> L1 ++ L2.


来源:https://stackoverflow.com/questions/5339176/erlang-operator-syntactic-sugar-or-separate-operation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!