Cut
This section is quite advanced. Only go on if you feel really comfortable with the rest of todays exercises.
Given the following knowledge base, which answers will Prolog
give when asked the query wizard(X)
?
wizard(harry). wizard(ron). wizard(hermione).(Download this knowledge base.)
Now, consider the following variants of this knowledge base.
- Variant 1:
wizard(harry) :- !. wizard(ron). wizard(hermione).
(Download this knowledge base.)- Variant 2:
wizard(harry). wizard(ron) :- !. wizard(hermione).
(Download this knowledge base.)- Variant 3:
wizard(harry). wizard(ron). wizard(hermione) :- !.
(Download this knowledge base.)
wizard(X)
.
As you have seen the exclamation mark has an effect on the number of answers that Prolog gets. The exclamation mark is called cut. It is a built-in predicate which always succeeds, but which has important side effects: it restricts backtracking. More specifically, when Prolog encounters a cut in a rule such as
q :- p1,...,pn,!,r1,...,rm,then it commits itself to using this particular clause for predicate
q
and it
commits itself to all choices made when evalauting
p1,...,pn
. That is, backtracking will not consider
alternative ways of proving the goals p1,...,pn
nor
will it consider alternative ways of proving q
, even
if it turns out later that the clause cannot be proved.
Backtracking is allowed though to check for
alternatives of the goals r1,...,rm
and to check for
alternatives of the goals that were considered before the
predicate q
was called.
Here are again several variants of the same knowledge base. Pose
the query p(X,Y)
and try to understand why Prolog
answers the way it does. Do a trace.
- Variant 1:
q(a). q(b). r(1). r(2). r(3). p(X,Y) :- q(X), r(Y).
(Download knowledge base.)- Variant 2:
-
q(a). q(b). r(1). r(2). r(3). p(X,Y) :- !, q(X), r(Y).
(Download knowledge base.) - Variant 3:
-
q(a). q(b). r(1). r(2). r(3). p(X,Y) :- q(X), !, r(Y).
(Download knowledge base.) - Variant 4:
-
q(a). q(b). r(1). r(2). r(3). p(X,Y) :- q(X), r(Y), !.
(Download knowledge base.)
You can find more about cuts in Chapter 10 of Learn Prolog Now!.