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:
- X and Y are neighbors if
- X lives in such town
- Y lives in such town
- 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:
- write: displays a string of characters.
- forall: find the list of all the facts that fulfill the condition as the first parameter, and for each element of this list, execute the instruction given as a second parameter.
- format: a more elaborate form of write that displays a text with a given format. Similar to printf in C
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 ...