Lists are a special kind of compound term. Lists are defined inductively:
[]
is a list, denoting the empty list.Ls
is a list, then the term '.'(L, Ls)
is also a list.There is a special syntax for denoting lists conveniently in Prolog:
'.'(a, '.'(b, '.'(c, [])))
can also be written as [a,b,c]
.'.'(L, Ls)
can also be written as [L|Ls]
.These notations can be combined in any way. For example, the term [a,b|Ls]
is a list iff Ls
is a list.
Creating lists
A list consisting of literals unified with the variable List:
?- List = [1,2,3,4].
List = [1, 2, 3, 4].
Building a list by consing:
?- Tail = [2, 3, 4], List = [1|Tail].
Tail = [2, 3, 4],
List = [1, 2, 3, 4].
Building a list of unknown values using the built-in length/2
:
?- length(List,5).
List = [_G496, _G499, _G502, _G505, _G508].
Since in Prolog everything is in essence a Term, lists behave heterogeneous:
?- List = [1, 2>1, this, term(X), 7.3, a-A].
List = [1, 2>1, this, term(X), 7.3, a-A].
This means a list can also contain other lists, also called inner lists:
List = [[1,2],[3,[4]]].