Prolog Tutorial: A problem is espressed in the form of rules

A prolog program consists primarily of facts and rules. The rules are the means of expressing what one wants to do with the facts that are recorded.

For example, we know in which cities live a group of people ...

dwells('Julia', 'New York').
dwells('Tom', 'San Francisco').
dwells('Naomi', 'New York').
dwells('Harrison', 'San Francisco').

Julia lives in New York, Tom in San Francisco, etc ...

One way to use this knowledge may be to find out what people live in the same city. For that we define a rule.

neighbor(X,Y) :- dwells(X, Town), dwells(Y, Town).

This is stated as follows:

  1. X and Y are neighbors if
  2. X lives in such town
  3. Y lives in such town
  4. de facto the variable Town has the same content in both statements

This will give us Julia Noami's neighbor, Harrison's neighbor Tom. But it will also give Julia Julia's neighbor, because prolog does not assume that X and Y are two different people. A condition to add is that the variables X and Y have different values.

neighbor(X,Y) :- dwells(X, Town), dwells(Y, Town), X \= Y.

We will have the following results.

Julia neighbor of Naomi 
Tom neighbor of Harrison
Naomi neighbor of Julia
Harrison neighbor of Tom

To display these results, we will make a small program. A program is a rule that contains instructions. We use three instructions from the standard library:

Here is the program:

program :-
write('Neighbors...\n'),
forall(neighbor(X,Y), format("~a neighbor of ~a ~n", [X, Y])),
write('End').

Since "program" is a rule, to execute it you type the following line in the prolog console:

program.

This will display:

Neighbors...
Julia neighbor of Naomi 
Tom neighbor of Harrison
Naomi neighbor of Julia
Harrison neighbor of Tom End

You can also directly invoke the "neighbor" rule:

neighbor('Julia', 'Naomi').

that will return "yes".

Knowing now how to state facts and rules, you have everything you need to solve complex problems with Prolog ...

  1. Prolog Tutorial: Recording a set of facts.
  2. Prolog Tutorial: A problem is espressed in the form of rules.
  3. Prolog demo: Looking for an apartment in a catalog.