66443 Programming Languages

Lecture Notes 4 November 1997

Logic Programming III

Unification

Search Trees: a Way of Diagramming Prolog's Backtracking

A List Processing Example

Consider the appnd predicate, which is true if its third argument is a list that is the concatenation of its first two arguments.

appnd([],L,L).
appnd([H | T],L,[H | TL]) :-
           appnd(T,L,TL).

Here are some examples of the use of this predicate:

blackbox.cs.rpi.edu% prolog

Aquarius Prolog version 1.0 top-level (SPARC, SunOS)

| ?- consult('appnd.pro').

yes

| ?- appnd([1], [2, 3], [1, 2, 3]).

yes

| ?- appnd([1], [2, 3], [1, 2, 4]).

no

| ?- appnd([1], X, [1, 2, 4]).

X = [2,4] ;

no
Here the semicolon was typed by the user to cause prolog to search for further solutions. There were no others. But if we use two variables we can find all possible combinations of lists whose concatenation is [1, 2, 4], by typing semicolons until all combinations have been displayed:
| ?- appnd(X, Y, [1, 2, 4]).

X = [],
Y = [1,2,4] ;

X = [1],
Y = [2,4] ;

X = [1,2],
Y = [4] ;

X = [1,2,4],
Y = [] ;

no

| ?-

A good exercise is to draw the backtracking tree that Prolog builds in producing these solutions.