[erlang-questions] ++ operator

Daniel Luna daniel@REDACTED
Wed Oct 31 18:57:04 CET 2012


It's not an optimization. This is how lists and append work.

1> [] ++ {}.
{}
2> [a] ++ {}.
[a|{}]

basically the documentation for append should read "conses each
element in List1 to List2".

Similar behaviour can also be seen when using cons itself.  As in:

3> [a | b].
[a|b]

which places 'b' where [] normally is.

Note that length is not possible on these improper lists:

4> length([a | b]).
** exception error: bad argument
     in function  length/1
        called as length([a|b])

while is_list will say true.

5> is_list([a | b]).
true

The last case is true because is_list should be read as is_cons_or_nil.

Note that this would not really give any guarantees with your
recommended guard since append([a], [a | b]) would still be legal
while being an improper list.

All this makes sort of sense if you assume that append is implemented as

append(List1, List2) ->
   do_append(reverse(List1), List2).

do_append([Hd | Tl], List2) ->
  do_append(Tl, [Hd | List2]);
do_append([], List2) ->
  List2.

Awaiting comment from Kostis about why improper lists are bad... :-)

Fun fact: Common LISP does the exact same thing when it comes to
append and cons.

Cheers,

Daniel



On 31 October 2012 13:24, Michał Ptaszek <erlang@REDACTED> wrote:
> Hey,
>
> I ran into a weird bug in my system (R15B02), namely I was trying to
> append a non-list item to a tail of the list by running:
> List ++ Item
>
> Nonetheless, as long as the list is empty the result of this expression is:
> [] ++ Item == Item
>
> For instance:
> 3> [] ++ {a, b}.
> {a,b}
>
> On the other hand,
> 5> a ++ [].
> ** exception error: bad argument
>      in operator  ++/2
>         called as a ++ []
>
> Does Erlang have a built-in optimizations such as?:
> ++([], B) -> B;
> ++(A, B) -> lists:append([A, B]).
>
> If so, it would be nice to add a guard:
> ++([], B) when is_list(B) -> B;
> ++(A, B) -> lists:append([A, B]).
>
> Kind regards,
> Michal Ptaszek
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions



More information about the erlang-questions mailing list