0203. Introduction to Artificial Intelligence

Prolog (2)

 

1. Lists

List is a very useful data structure in Prolog. A list is a sequence of arguments written within a pair of square brackets. An argument can be a constant, a variable, or a list.

Examples of lists: [a, b, c], [biking, swimming], [X, a, mary], [], [1, [2, 3], Y].

Prolog uses a "bar operator" to indicate "the rest of the list". In list [X | Y], X indicates the first element of the list, and Y indicates the rest of the list (which is a list itself).

After defining the following facts:

my_lists([a, b, c]).
my_lists([biking, swimming]).
my_lists([X, a, mary]).
my_lists([]).
my_lists([1, [2, 3], Y]).
we get the following running log:
?- my_lists([X|Y]).

X = a
Y = [b, c] ;

X = biking
Y = [swimming] ;

X = _G157
Y = [a, mary] ;

X = 1
Y = [[2, 3], _G235] ;

No
?- my_lists([A1,A2|A3]).

A1 = a
A2 = b
A3 = [c] ;

A1 = biking
A2 = swimming
A3 = [] ;

A1 = _G157
A2 = a
A3 = [mary] ;

A1 = 1
A2 = [2, 3]
A3 = [_G253] ;

No
An identifier proceeded by a "_" represents an internal variable.

 

2. List processing

In Prolog, a predicate on list is usually defined recursively, that is, by reducing the relation to another one on a shorter list, until a boundary situation, where the relation is specified directly.

The following is a typical Prolog program:

/* member(X, Y) is true iff X is an element of list Y. */

member(X, [X | _]).
member(X, [_ | T]) :- member(X, T).
In the program "_" is an anonymous variable.

A more powerful program:

/* append(X, Y, Z) is true iff list Z equals X and Y appended together */

append([ ], L, L).
append([H | T], L, [H | R]) :- append(T, L, R).
Different ways to use the program:
?- append([a, b], [c, d], [a, b, c, d]).
Yes

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

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

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

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

?- append(X, Y, [a, b]).
X = []
Y = [a, b];
X = [a]
Y = [b];
X = [a, b]
Y = [];
No
Compared with procedural programming language, a Prolog program often implements more than one functions, because it allows the input/output distinction among arguments to be determined at run time.