[erlang-questions] List pipe syntax

Robert Virding robert.virding@REDACTED
Thu Dec 21 10:45:02 CET 2006

I think there is one thing that you must realise with the [Head|Tail] 
construction. It actually builds a pair in which the Head and Tail can 
be any term. However, Erlang has extra support, both syntax and 
libraries, for a specific usage of pirs, as lists. I.e. where the tail 
is a list (pair) or []

So syntax-wise:

[1] is syntactic sugar for [1|[]]
[1,2]       -"-            [1|[2|[]]]
[1,b,2]     -"-            [1|[b|[2|[]]]]
[1,2|Tail]  -"-            [1|[2|Tail]]

This also shows why you can use the [Head|Tail] to add an element to the 
front of a list or match a list and remove the first element (the head).

Also all library functions on lists assume and support this usage, as do 
most (all?) applications which use lists.

The is_list/1 test just tests that the top level of its argument is 
either a [H|T] or a [], it does not do a deep test.

This means that you can actually use pairs to build data general 
structures although this is not recomended as it can easily confuse 
people. Use tuples instead. In Lisp however this usage of conses (what 
they are called in Lisp) is common.


Alexander Harju wrote:
> Hi,
> I have a question about the pipe syntax when building lists.
> According to the Erlang reference a list is either the empty list [] or
> consists of a head and a tail which is also a list. [Head|Tail].
> I've noticed that you can do some weird "list"-building using the pipe
> syntax.
> [1|[]] is obviously a list according to the definition since [] is a list.
> But what about [1|2]??. This shouldn't evaluate to a list since 2 isn't a
> list. I checked it with erlang:is_list([1|2]) which returned true. You can
> also use the matching [H|T] = [1|2] where H is bound to 1 and T is bound
> to 2. [1|2] == [1,2] returns false.
> I figured that [1|2] was evaluated to a list of length 1 with the strange
> element 1|2, but erlang:length([1|2]) exits with a badarg.
> It's definitely not a list, but what is it then and why does
> erlang:is_list return true?
> // Alex
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions

More information about the erlang-questions mailing list