Lists in Prolog

“We like lists because we don’t want to die.”
—Umberto Eco

Prolog has a number of useful built-in relations for working with lists. These include:

RelationDescription
append(X, Y, Z)True if appending lists X and Y yields Z
reverse(X, Y)True if list X is the reverse of list Y
permutation(X, Y)True if list X is a permutation of list Y
sort(X, Y)True if list Y is the sort of list X
length(L, N)True if list L has integer length N
member(X, Y)True if X is an element of list Y

Example

Here are some examples of queries involving lists:

  1.  

    ?- length([a,b,c,d], 4).`

    Succeeds.

  2.  

    ?- length([a,b,c], 4).

    Fails.

  3.  

    ?- length([a,b,c], N).

    Succeeds with N = 3

  4.  

    ?- length(L, 0).

    Succeeds with L = []

  5.  

    ?- member(c, [a,b,c,d]).

    Succeeds.

  6.  

    ?- member(e, [a,b,c,d]).

    Fails.

  7.  

    ?- member(X, [a,b,c,d]).

    Can succeed in four ways,
    namely X = a or X = b or X = c or X = d.

  8.  

    ?- append([a], [b,c,d], L).

    Succeeds with L = [a,b,c,d]

  9.  

    ?- append(X, Y, [a,b,c,d]).

    Can succeed in five ways, namely
    X = [], Y = [a,b,c,d], or
    X = [a], Y = [b,c,d], or …