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

zxq9 zxq9@REDACTED
Tue Feb 24 16:53:01 CET 2015


On 2015年2月24日 火曜日 08:37:38 Cole Fichter wrote:
> I came across the example:
> > [1,2|3].
> 
> [1,2|3]
> 
> 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.
> 
> But what exactly is happening in the example above? Why does the evaluated
> expression still contain the pipe?
> 
> My best guess is that the final expression results in a match specification
> that could be used in a pattern match. However, that seems strange too
> because if so, we'd be popping two items off the list, which should be
> illegal.
> 
> Can someone shed some light?

It is entirely acceptable to match an arbitrary number of items off the top of 
a list, provided there are at least as many in the list:

1> SomeList = [1, 2, 3, 4, 5, 6].
[1,2,3,4,5,6]
2> [A, B, C | Rest] = SomeList.
[1,2,3,4,5,6]
3> A.
1
4> B.
2
5> C.
3
6> Rest.
[4,5,6]

Profoundly useful in some cases.

-Craig



More information about the erlang-questions mailing list