Summery for Chapter 6
6.1 Looping a Fixed Number of Times
Many programming languages provide 'for loops' which enable a set of instructions to be executed a fixed number of times. No such facility is available in Prolog (directly), but a similar effect can be obtained using recursion.
6.2 Looping Until a Condition Is Satisfied
Many languages have an 'until loop' which enables a set of instructions to be executed repeatedly until a given condition is met. Again, no such facility is available directly in Prolog, but a similar effect can be obtained in several ways.
6.2.1 Recursion
Shows the use of recursion to read terms entered by the user from the keyboard and output them to the screen, until end is encountered.
6.2.2 Using the 'repeat' Predicate
Although it can often be used to great effect, recursion is not always the easiest way to provide the types of looping required in Prolog programs. Another method that is often used is based on the built-in predicate repeat.
The goal repeat does not repeat anything; it merely succeeds whenever it is called. The great value of repeat is that it also succeeds (as many times as necessary) on backtracking. The effect of this, as for any other goal succeeding, is to change the order of evaluating goals from 'right to left' (i.e. backtracking) back to 'left-to-right'. This can be used to create a looping effect.
6.3 Backtracking with Failure
As the name implies, the predicate fail always fails, whether on 'standard' evaluation left-to-right or on backtracking. Advantage can be taken of this, combined with Prolog's automatic backtracking, to search through the database to find all the clauses with a specified property.
6.3.1 Searching the Prolog Database
Supposing the database contains clauses
6.3.2 Finding Multiple Solutions
Backtracking with failure can also be used to find all the ways of satisfying a goal. Suppose that a predicate findroute(Town1,Town2,Route) finds a route Route between two towns Town1 and Town2. The details of this predicate are irrelevant here. It may be assumed that Town1 and Town2 are atoms and that Route is a list.