Senin, 07 Desember 2009

LOOPS

Most conventional programming languages have a looping facility that enables a set of instructions to be executed repeatedly either a fixed number of times or until a given condition is met. In Prolog, this can be done in a variety of ways, using backtracking, recursion, built-in predicates, or a combination of these.

1. Looping a Fixed Number of Times
No such facility is available in Prolog (directly), but a similar effect can be obtained using recursion,

2. Looping Until a Condition Is Satisfied
Again, no such facility is available directly in Prolog, but a similar effect can be obtained in several ways.
1. Recursion
The function of recursion is to read terms entered by the user from the keyboard and output them to the screen, until end is encountered. This recursive program repeatedly prompts the user to enter a term until either yes or no is entered.
2. Using the 'repeat' Predicate
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.
This program repeatedly prompts the user to enter a term until either yes or no is entered. It is an alternative to the recursive program shown at the end of the previous section. In this case it is debatable whether using repeat is an improvement on using recursion.
Goals to the left of repeat in the body of a clause will never be reached on backtracking. The next program reads a sequence of terms from a specified file and outputs them to the current output stream until the term end is encountered. This program shows how to implement a menu structure which loops back repeatedly to request more input. Entering go at the prompt causes Prolog to output a menu from which the user can choose activities one at a time until option d is chosen. Note that all inputs are terms and so must be followed by a full stop character.
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.
1. Searching the Prolog Database
2. Finding Multiple Solutions


This chapter describes how a set of goals can be evaluated repeatedly in Prolog, either a fixed number of times or until a specified condition is met, and how multiple solutions can be arrived at using the technique of 'backtracking with failure'.

Tidak ada komentar:

Posting Komentar