Prolog provides a way to make the head and tail of a list explicit. Instead of separating elements with commas, you can separate the head and tail with a vertical bar (|). For instance,
[a, b, c] is equivalent to [a|[b, c]]
and, continuing the process,
[a|[b,
c]] is equivalent to [a|[b|[c]]]
which is equivalent to [a|[b|[c|[]]]]
You can even use both kinds of separators in the same list, provided the vertical bar is the last separator. So, if you really want to, you can write [a, b, c, d] as [a, b|[c, d]]. Table 7.1 gives more examples.
Table 7.1: Heads and Tails of Lists
List |
Head |
Tail |
['a', 'b', 'c'] |
'a' |
['b', 'c'] |
[ 'a' ] |
'a' |
[] /* an empty list */ |
[ ] |
undefined |
undefined |
[[1, 2, 3], [2, 3, 4], []] |
[1, 2, 3] |
[[2, 3, 4], []] |
Table 7.2 gives several examples of list unification.
Table 7.2: Unification of Lists
List 1 |
List 2 |
Variable Binding |
[X, Y, Z] |
[egbert, eats, icecream] |
X=egbert, Y=eats, Z=icecream |
[7] |
[X | Y] |
X=7, Y=[] |
[1, 2, 3, 4] |
[X, Y | Z] |
X=1, Y=2, Z=[3,4] |
[1, 2] |
[3 | X] |
fail |