[erlang-questions] What does it mean when an evaluated expression is a list that contains the pipe character?

Richard A. O'Keefe ok@REDACTED
Wed Feb 25 01:14:56 CET 2015


On 25/02/2015, at 4:37 am, Cole Fichter <cole.fichter@REDACTED> wrote:
> 
> I understand that the pipe character, |, can be used to append an item to the head of the list or to pop an item off the list in a pattern match.

Just a point on terminology:  [x] ++ [y,z] is APPENDING (concatenating two lists);
[x | [y,z]] is CONSING.

> But what exactly is happening in the example above? Why does the evaluated expression still contain the pipe?

This goes back to about 1959.
There is no spoon.  Sorry, there are no lists.

THERE ARE ONLY PAIRS.

Lisp   : (car  . cdr)
Prolog : [Head | Tail]
Erlang : [Head | Tail]

There is a convention in Lisp   that . () need not be mentioned.
There is a convention in Prolog that | [] need not be mentioned.
There is a convention in Erlang that | [] need not be mentioned.
There is a convention in Lisp   that (a . (b . <stuff>)) abbreviates as (a b . <stuff>).
There is a convention in Prolog that [a | [b | <stuff>]] abbreviates as [a,b | <stuff>].
There is a convention in Erlang that [a | [b | <stuff>]] abbreviates as [a,b | <stuff>].

The so-called "list" [1,2,3] is *really* [1|[2|[3|[]]]].
[1,2,3] is just an abbreviation for convenience.

EVERY non-empty list "still contain(s) the pipe".
It's just that when the ultimate tail happens to be the
empty list, it will not be shown.

[1,2|3] is no different in its structure from
[1,2|[]], it's just that [1,2|[]] will be
DISPLAYED without the |[] part.  BUT IT IS STILL THERE.

> My best guess is that the final expression results in a match specification that could be used in a pattern match.

I'm having difficulty understanding this.  There is nothing in the least special
about [1,2|3].  It is just a pair whose head is 1 and whose tail is
a pair whose head is 2 and whose tail is 3.  It's just a boring old plain old
data structure.

>  However, that seems strange too because if so, we'd be popping two items off the list, which should be illegal.

There is no such thing as "popping".  You cannot change the list [1,2,3]
any more than you can change the number 137.  You can *recognise* that it
has a certain form and *extract* information from it, but you can't *change* it.
The pattern match [A,B|Rest] = [1,2,3] is perfectly legal and will bind
A = 1, B = 2, Rest = [3].  The pattern match [X,Y|More] = [1,2|3] is also
perfectly legal and will bind X = 1, Y = 2, More = 3.

Why would you think that "popping" two items off a list that _has_ two
items should be illegal?

It all makes sense when you realise that there are no lists, only pairs.





More information about the erlang-questions mailing list