3203. Introduction to Artificial Intelligence

Prolog (3)

 

1. How Prolog works

Prolog works by repeatedly processing goals (queries). A goal can be directly achieved by a matching fact, or indirectly achieved if all of its derived (sub)goals are achieved.

A goal derivation happens if the goal matches the head of a rule, then the body of the rule becomes a sequence of goals. Variable unification may happen during the matching process.

When processing a goal, the program (database) is scanned from top to bottom; when a sequence of goals are processed, the order is from left to right.

If a goal in a sequence fails, the one on its left is continued to look for another success. This is called "backtrack", and it will undo the variable unifications in the previous step.

For example, given likes2.pl:

likes(george, swimming).
likes(susie, tennis).
likes(susie, swimming).
likes(mary, X) :- likes(susie, X), likes(george, X).
The goal "?- likes(mary, Y)." will cause a backtrack in the body of the rule.
?- trace, likes(mary, Y).
   Call: (7) likes(mary, _G3014) ? creep
   Call: (8) likes(susie, _G3014) ? creep
   Exit: (8) likes(susie, tennis) ? creep
   Call: (8) likes(george, tennis) ? creep
   Fail: (8) likes(george, tennis) ? creep
   Redo: (8) likes(susie, _G3014) ? creep
   Exit: (8) likes(susie, swimming) ? creep
   Call: (8) likes(george, swimming) ? creep
   Exit: (8) likes(george, swimming) ? creep
   Exit: (7) likes(mary, swimming) ? creep
Y = swimming.

To understand the process, sometimes it is helpful to draw a derivation tree.

 

2. Procedural interpretation

Previously we gave a Prolog program a declarative interpretation, according to which a fact is a relation among its arguments, a rule indicates the conditions for a relation to hold, and a goal is a conclusion to be verified.

A Prolog program also has a procedural interpretation, according to which a fact is an executable operation, a rule reduces an operation into a sequence of sub-operations, and a goal is an operation to be executed.

In this way, a Prolog program can describe an algorithm, like in a procedural language.

For example, see how to solve the Towers of Hanoi puzzle in Prolog.

Another example: factorial function.

 

3. Built-in predicates

Prolog has a set of "built-in" predicates for various purposes.

 

4. Prolog and predicate calculus

Prolog implements some of the inference rules in predicate calculus.