Prolog (3)
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.
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.