Download 1. Logic Programming and Prolog: A First Glimpse

Transcript
Logic Programming and Prolog
51
______________________________________________________________
The repetition in failure-driven loops is due to a predicate, in our example
grand_parent/2, which produces several solutions using backtracking.
There is a funny predicate, repeat/0, which does nothing else than producing an unlimited
number of alternative solutions by backtracking. It is defined as follows:
repeat/0 must be used with a goal that plays the role of an 'until' statement in other
programming languages. The following example demonstrates the technique:
do_squares :write('Squares. Enter 0 to stop the loop.'), nl,
repeat,
write('x
='), read(X),
Y is X*X,
write('x^2 = '), write(Y), nl,
X = 0, !.
In some Prolog systems, failure-driven interactive loops are more efficiently implemented
than tail-recursion based loops. This may be important for cases like mouse event responses
and the like.
We conclude this discussion about loops with a construct similar to a for-loop in other
programming languages. The following predicate generates all integers in a given interval by
backtracking. In many implementations, the predicate is predefined.
% between(Low,High,Value) :- Low and High are integers,
%
High >= Low. If Value is bound to an integer,
%
Low <= Value <= High. When Value is a variable it is
%
successively bound to all integers from Low to High.
Using this predicate, we can write a program that prints all prime numbers of a given interval:
% primes(L,H) :- print the prime numbers in L..H
We have shown that failure-driven loops can be used to collect alternative solutions created
by backtracking. We can, for instance, write the solutions to the terminal (or a file). However,
with the techniques we have seen so far, we cannot put the solutions in a list or another data