Example 1
The following program outputs integers from a specified value down to 1.
Note: Must be M is N-1, loop (M). Because loop(N-1) will not work.
The result is like this:
?- loop(6).
The value is: 6
The value is: 5
The value is: 4
The value is: 3
The value is: 2
The value is: 1
yes
Example 2
The next program outputs integers from First to Last inclusive.
Here output_values has two arguments, which can be read as 'output the integers from First to Last inclusive'. The loop terminates when both arguments are the same.
?- output_values(5,12).
56789
10
11
12
end of example
yes
Example 3
Define a predicate to find the sum of the integers from 1 to N.
…………………………………………………………………………….
The sum of the first 3 integers is the sum of the first 2 integers, plus 3.
The sum of the first 2 integers is the sum of the first 1 integers, plus 2.
The sum of the first 1 integers is one.
?- sumto(100,N).
N = 5050
?- sumto(1,1).
yes
N = 5050
?- sumto(1,1).
yes
2. Looping Until a Condition Is Satisfied
2.1 Recursion
The first example below 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.?- go.
Type end to end: university.
Input was university
Type end to end: of.
Input was of
Type end to end: portsmouth.
Input was portsmouth
Type end to end: end.
Input was end
yes
Type end to end: university.
Input was university
Type end to end: of.
Input was of
Type end to end: portsmouth.
Input was portsmouth
Type end to end: end.
Input was end
yes
Use disjunction ;, we can write in one clause:
2.2 Using the 'repeat' Predicate
Below is an example predicate that the goal is get asnwer 'yes' or 'no'.
?- get_answer(X).
Enter answer to question
answer yes or no: unsure.
answer yes or no: possibly.
answer yes or no: no.
answer is no
X = no
Enter answer to question
answer yes or no: unsure.
answer yes or no: possibly.
answer yes or no: no.
answer is no
X = no
3. Backtracking with Failure
3.1 Searching the Prolog Database
Supposing the database contains clauses such as :
Each dog clause can be processed in turn using the alldogs predicate defined below.
?- alldogs.
fido is a dog
fred is a dog
jonathan is a dog
yes
fido is a dog
fred is a dog
jonathan is a dog
yes
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.
Backtracking with failure can then be used to find all possible routes between Town1 and Town2 and write out each one on a separate line, as follows:
Backtracking with failure can then be used to find all possible routes between Town1 and Town2 and write out each one on a separate line, as follows:

Tidak ada komentar:
Posting Komentar