Information Technology Reference
In-Depth Information
The
append
predicate can also be used to generate lists:
% What pairs of lists when joined give [a,b,c]?
?- append(X,Y,[a,b,c]).
X = [],
Y = [a, b, c]
;
X = [a],
Y = [b, c]
;
X = [a, b],
Y = [c]
;
X = [a, b, c],
Y = []
;
No
Using
append
to generate a pair of lists in this way is a very useful technique. (In
chapter 8, it is used to break up a list of words into phrases.) Variables can also be
used freely within the arguments to
append
:
% [a,b] joined to what list L gives [a,b,c,d,e,f]?
?- append([a,b],L,[a,b,c,d,e,f]).
L = [c, d, e, f]
% Solve for the variables X, Y, and L.
?- append([X,b],[d|L],[a,_,Y,e,f]).
X=a, L=[e,f],Y=d
The
append
predicate is quite powerful, and a number of additional predicates can be
defined with it. Here are some one-line examples:
The predicate
front(L1,L2)
holds if the list
L1
is the start of list
L2
:
front(L1,L2) :- append(L1,_,L2).
The predicate
last(E,L)
holds if
E
is the last element of list
L
:
last(E,L) :- append(_,[E],L).
Yet another version of the
member
predicate:
elem2(E,L) :- append(_,[E|_],L).
This definition of
elem2
says that
E
is an element of list
L
if
L
is the result of joining
something (the first
_
) with a list whose head is
E
and whose tail is something (the
second
_
). In other words,
E
is an element of
L
if
L
is a list that has some number of
elements, then
E
, then some number of other elements.
As with the
member
predicate, one needs to be careful not to generate an infinite set
of candidate values. Consider this version of a predicate that determines whether one
element appears
before
another in a list:
% A first version
before(X,Y,L) :- append(_,[X|_],Z), append(Z,[Y|_],L).